suneetha
suneetha

Reputation: 11

how to convert date into utc milliseconds with timezone in javascript

getTime() Is it return local or UTC milliseconds?

var startDate = new Date(); 
var val = (startDate.getTime()).toString();

Below logic will return UTC millisecords:

var startDate = new Date(); 
var val = (new Date(Date.UTC(
    startDate.getFullYear(),
    startDate.getMonth(),
    startDate.getDate(),
    startDate.getHours(),
    startDate.getMinutes(),
    startDate.getSeconds()
))).getTime().toString(); 

Need script for converting the date to UTC milliseconds with timezone like America/Los_Angeles

Upvotes: 1

Views: 1283

Answers (1)

Bahadir Tasdemir
Bahadir Tasdemir

Reputation: 10783

Here you create a new date:

var startDate = new Date();

This is set to your browsers current timezone, here mine is Turkey:

Fri Sep 02 2016 17:50:06 GMT+0300 (Turkish Summer Time)

If you convert this string Fri Sep 02 2016 17:50:06 GMT+0300 into millis then you will have the value with the GMT+0300:

Date.parse("Fri Sep 02 2016 17:50:06 GMT+0300")
>> 1472827806000

Here, you can create your date object with a different timezone and get the millis of it, let's say it is America/Los_Angeles:

1) Create date object

var d = new Date();

2) Get the local time value

var localTime = d.getTime();

3) Get the local offset

var localOffset = d.getTimezoneOffset() * 60000;

4) Obtain UTC

var utc = localTime + localOffset;

5) Obtain the destination's offset, for America/Loas_Angeles it is UTC -7

var offset = -7; 
var ala = utc + (3600000*offset);

6) Now ala contains the milis value of America/Los_Angeles. Finally convert it to a new date object if needed:

var nd = new Date(ala);

Final: Now you can get the miliseconds of the new date object:

nd.getTime();
//or
ala;

Upvotes: 1

Related Questions