UTC date and time for local

I am writing a function to cancel UTC local time

function utcToLocal(utc){ var t = new Date(Number(utc)); d = [t.getFullYear(), t.getMonth(), t.getDate()].join('/'); d += ' ' + t.toLocaleTimeString(); return d; } 

but I can’t confirm that this code is right?

+4
source share
1 answer

You should be able to convert the UTC timestamp to a local date and just subtract the local offset (which is in minutes), therefore:

 function utcToLocal(utc){ // Create a local date from the UTC string var t = new Date(Number(utc)); // Get the offset in ms var offset = t.getTimezoneOffset()*60000; // Subtract from the UTC time to get local t.setTime(t.getTime() - offset); // do whatever var d = [t.getFullYear(), t.getMonth(), t.getDate()].join('/'); d += ' ' + t.toLocaleTimeString(); return d; } 

Where am I, the offset is -600, so I need to subtract -36,000,000 ms from UTC time (which actually adds 36,000,000 ms).

Edit

Perhaps I misunderstood this question.

The internal value of the javascript date instance is the UTC time click in milliseconds. Therefore, if utc is such a time (for example, 2012-08-19T00: 00: 00Z - 1345334400000), then the OP will create a date instance based on this value, and toLocaleTimeString display an implementation-dependent local time string for the supplied UTC time.

So, if the local time zone offset is -6 hours, then alert(new Date(1345334400000))) shows something like Sat 08/18/2012 18:00:00 GMT-600.

I assumed that the OP wanted to set local time at the same time as UTC, for example. that 2012-08-19T00: 00: 00Z will become 2012-08-19T00: 00: 00 local.

+5
source

All Articles