F21
F21

Reputation: 33421

Parsing dates without timezone conversion

I am working with groovy (gremlin to traverse a graph database to be exact). Unfortunately, because I am using gremlin, I cannot import new classes.

I have some date values that I wish to convert to a Unix timestamp. They are stored as UTC in the format: 2012-11-13 14:00:00:000

I am parsing it using this snippet (in groovy):

def newdate = new Date().parse("yyyy-M-d H:m:s:S", '2012-11-13 14:00:00:000')

The problem is that it does a timezone conversion, which results in:

Tue Nov 13 14:00:00 EST 2012

And if I then convert that to a timestamp using time(), that gets converted to UTC, then the timestamp generated.

How do I get new Date() to not do any timezone conversions when the date is first parsed (and just assume the date as UTC)?

Upvotes: 16

Views: 47669

Answers (3)

exody
exody

Reputation: 81

I used Calendar to avoid timezone conversion. Although I did not use new Date(), the result is the same.

String dateString = "2012-11-13 14:00:00:000";
Calendar calendar = Calendar.getInstance();
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-M-d H:m:s:S");
calendar.setTime(sdf.parse(dateString));
sdf.setTimeZone(TimeZone.getTimeZone("UTC"));
Date date = calendar.getTime();

Upvotes: 1

Pankaj
Pankaj

Reputation: 5250

Date class parse(String str) is deprecated from JDK 1.1, try SimpleDateFormat class that supports TimeZone and Locale settings too.

Upvotes: -1

jahroy
jahroy

Reputation: 22692

Here are two ways to do it in Java:

/*
 *  Add the TimeZone info to the end of the date:
 */

String dateString = "2012-11-13 14:00:00:000";
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-M-d H:m:s:S Z");
Date theDate = sdf.parse(dateString + " UTC");

/*
 *  Use SimpleDateFormat.setTimeZone()
 */

String dateString = "2012-11-13 14:00:00:000";
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-M-d H:m:s:S");
sdf.setTimeZone(TimeZone.getTimeZone("UTC"));
Date theDate = sdf.parse(dateString);

Note that Date.parse() is deprecated (so I did not recommend it).

Upvotes: 20

Related Questions