Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to make date.getTime() returns UTC time?

Tags:

I have a Date object which represents a UTC time. When I use the method getTime() to get the long value of this object, the value returned corresponds to our local time (central US). What is the correct way to get the value back which corresponds to the original UTC time?

Thanks

like image 484
flyingfromchina Avatar asked Mar 08 '10 17:03

flyingfromchina


People also ask

Does getTime return UTC?

Use the getTime() method to get a UTC timestamp, e.g. new Date(). getTime() . The method returns the number of milliseconds since the Unix Epoch and always uses UTC for time representation. Calling the method from any time zone returns the same UTC timestamp.

How do you convert date to UTC format?

To convert a JavaScript date object to a UTC string, you can use the toUTCString() method of the Date object. The toUTCString() method converts a date to a string, using the universal time zone. Alternatively, you could also use the Date. UTC() method to create a new Date object directly in UTC time zone.

What does date getTime () do?

Javascript date getTime() method returns the numeric value corresponding to the time for the specified date according to universal time. The value returned by the getTime method is the number of milliseconds since 1 January 1970 00:00:00. You can use this method to help assign a date and time to another Date object.

What does getTime return date?

JavaScript Date getTime() getTime() returns the number of milliseconds since January 1, 1970 00:00:00.


1 Answers

The DateFormat class has a method for setting your preferred time zone, and there's a time zone class that has a setting for UTC time.

So, for example,

SimpleDateFormat sdf = new SimpleDateFormat(); sdf.setTimeZone(new SimpleTimeZone(SimpleTimeZone.UTC_TIME, "UTC")); Date yourUtcDate = sdf.parse(yourOriginalDate); 
like image 167
Pops Avatar answered Oct 05 '22 23:10

Pops