简体   繁体   中英

Date formatting

I have the following date format I need to parse:

Aug  6, 2013 18:34:16.990423000

So I tried the following:

Date startTime;
SimpleDateFormat df = new SimpleDateFormat("MMM dd, yyyy kk:mm:ss.S", Locale.ENGLISH);
startTime = df.parse("Aug  6, 2013 18:34:16.990423000");

But then mydate.toString gives me completely other date!

It gives me "Sun Aug 11 11:27:43 IDT 2013" !

Does it relate to time zone?

By the way, when I perform

ts = returnTime.getTime() - startTime.getTime();

it seems to return the correct answer. But I am not sure it is always so.

The problem is with the S which indicates milliseconds. It adds that number of milliseconds to the date but you have 990423000 milliseconds. You might want to leave out the .S of your format or truncate your input first as in the following example:

Date startTime;
String dateString = "Aug  6, 2013 18:34:16.990423000";
SimpleDateFormat df = new SimpleDateFormat("MMM dd, yyyy kk:mm:ss.SSS", Locale.ENGLISH);
startTime = df.parse(dateString.replaceFirst("\\.(\\d{3})\\d*$", ".$1"));
System.out.println(new SimpleDateFormat("MMM dd, yyyy kk:mm:ss.SSS").format(startTime));

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM