Alan Varghese Aniyan Alan Varghese Aniyan - 1 year ago 174
Javascript Question

How to get UTC date in milliseconds format similiar to new Date().getTime() in javascript?

To solve a time zone issue which is seen when I deploy my project,I need to convert my current date in millisecond format to corresponding UTC date in milliseconds.How can I solve it?

Answer Source

After trying different methods this is what I found to be most efficient and working solution.

       var d = new Date(); //d can be any date we need to convert.
       var millisec= d.getTime()+ (d.getTimezoneOffset() * 60000);

getTimeZoneOffset() returns the offset time in minutes


Actually the above code adds the offset to the local date (instead of subtracting) and my server (which is UTC) allows to get back the local time on the server.

I need the local time in server, as I realised later, we've local times in the API data that we use.

So coming back to the original question, a possible solution to convert local to UTC would be:

       var d = new Date(); //d can be any date we need to convert.
       var millisec= d.getTime() - (d.getTimezoneOffset() * 60000);

In another project later I used the below for date in string form:

a. to convert from local to UTC (while sending to server):

new Date().toUTCString()

b. to convert back to local (while getting data to web from server:

date.toLocaleDateString("en-AU", {
                weekday: 'short', year: 'numeric', month: 'short', day: 'numeric',
                hour12: false, hour: 'numeric', minute: 'numeric', second: 'numeric'
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download