jamee
jamee

Reputation: 573

How to convert this unix time string to java date

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!

Upvotes: 3

Views: 352

Answers (1)

T.J. Crowder
T.J. Crowder

Reputation: 1074148

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());

Upvotes: 3

Related Questions