Java Converting a Date to a Different Format

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?

Thanks!

You seem to be under the impression that a Date
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 Date
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 java.util.*
.

Hello, buddy!稿源:Hello, buddy! (源链) | 关于 | 阅读提示

本站遵循[CC BY-NC-SA 4.0]。如您有版权、意见投诉等问题,请通过eMail联系我们处理。
酷辣虫 » 综合编程 » Java Converting a Date to a Different Format

喜欢 (0)or分享给?

专业 x 专注 x 聚合 x 分享 CC BY-NC-SA 4.0

使用声明 | 英豪名录