Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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)?

like image 896
F21 Avatar asked Nov 15 '12 02:11

F21


People also ask

How can I date without a time zone?

To create a date without timezone:Get the ISO representation of the date string. Remove the Z character from the end of the ISO string. Pass the result to the Date() constructor.

What is parse date time?

Date.parse() The Date.parse() method parses a string representation of a date, and returns the number of milliseconds since January 1, 1970, 00:00:00 UTC or NaN if the string is unrecognized or, in some cases, contains illegal date values (e.g. 2015-02-31).

How to convert time format in JavaScript?

Use different Date methods to convert a date from one format to another format, e.g., to Universal Time, GMT, or local time format. The following example demonstrates ToUTCString() , ToGMTString() , ToLocalDateString() , and ToTimeString() methods to convert date into respective formats.


1 Answers

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).

like image 80
jahroy Avatar answered Oct 13 '22 11:10

jahroy