3

I got this time string "2015-07-16T03:58:24.932031Z", I need to convert to a java timestamp, I use the following code, seems the converted date is wrong?

public static void main(String[] args) throws ParseException {
    DateFormat format = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSSSSS'Z'");
    Date date = format.parse("2015-07-16T03:58:24.932031Z");
    System.out.println("date: " + date);
    System.out.println("timestamp: " + date.getTime());
}

output:

date: Thu Jul 16 04:13:56 CST 2015
timestamp: 1436991236031

Is my date format wrong?

Thanks in advance!

jamee
  • 553
  • 1
  • 5
  • 25
  • Please search StackOverflow before posting. Be assured that any basic question on date-time handling in Java has already been asked and answered. – Basil Bourque Aug 01 '15 at 18:24

1 Answers1

3

You don't want to quote the Z, it's a timezone indicator. Instead, use the X format specifier, for an ISO-8601 timezone.

Separately, you may want to pre-process the string a bit, because the part at the end, .932031, isn't milliseconds (remember, there are only 1000ms in a second). Looking at that value, it's probably microseconds (millionths of a second). SimpleDateFormat doesn't have a format specifier for microseconds. You could simply use a regular expression or other string manipulation to remove the last three digits of it to turn it into milliseconds instead.

This (which assumes you've done that trimming) works: Live Copy

DateFormat format = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSSX");
// Note --------------------------------------------------------^^^^
Date date = format.parse("2015-07-16T03:58:24.932Z");
// Note trimming --------------------------------^
System.out.println("date: " + date);
System.out.println("timestamp: " + date.getTime());
T.J. Crowder
  • 1,031,962
  • 187
  • 1,923
  • 1,875
  • result: date: Thu Jul 16 11:58:24 CST 2015 timestamp: 1437019104932 seems still not correct – jamee Aug 01 '15 at 08:03
  • @jamee: It's correct, it's just that you're in the CST timezone, so you're seeing the date interpreted in that timezone by the default `Date#toString`. That's an *output* issue, not an issue with the `Date` value. Normally you wouldn't use `Date#toString` (because **all** of `Date`'s timezone stuff has been deprecated for over a decade), you'd use `DateFormat` and/or `Calendar` and/or JodaTime and/or the various new date/time features in Java 8's [`java.time` package](http://docs.oracle.com/javase/8/docs/api/java/time/package-summary.html). – T.J. Crowder Aug 01 '15 at 08:29