I have a date string in this format:
String fieldAsString = "11/26/2011 14:47:31";
I am trying to convert it to a Date type object in this format: “yyyy.MM.dd HH:mm:ss”
I tried using the following code:
SimpleDateFormat sdf = new SimpleDateFormat("yyyy.MM.dd HH:mm:ss"); Date newFormat = sdf.parse(fieldAsString);
However, this throws an exception that it is an Unparsable date.
So I tried something like this:
Date date = new SimpleDateFormat("MM/dd/yyyy HH:mm:ss").parse(fieldAsString); String newFormat = new SimpleDateFormat("yyyy.MM.dd HH:mm:ss").format(date)
However, this new format is now in the ‘String’ format but I want my function to return the new formatted date as a ‘Date’ object type. How would I do this?
You seem to be under the impression that a
object has a format. It doesn’t. It sounds like you just need this:
Date date = new SimpleDateFormat("MM/dd/yyyy HH:mm:ss").parse(fieldAsString);
(You should consider specifying a locale and possibly a time zone, mind you.)
Then you’ve got your
value. A format is only relevant when you later want to convert it to text… that’s
when you should specify the format. It’s important to separate the value being represent (an instant in time, in this case) from a potential textual representation. It’s like integers – there’s no
difference between these two values:
int x = 0x10; int y = 16;
They’re the same value, just represented differently in source code.
Additionally consider using Joda Time
for all your date/time work – it’s a much cleaner API than