For last couple of days I am trying to get UTC timestamp in Node JS project. I referred lot of questions in SO too. Unfortunately Javascript does follows,
new Date()
-> Returns local time of the server. Not UTC.
Date.now()
-> Return local time of the server. Not UTC.
new Date().toISOString()
returns UTC string. But when I convert string to date object then Date()
converts it back to local time.
in Swift language I use Date().timeIntervalSince1970 * 1000
to active this and it works great.
In server I am using Node JS and I can't use local time. I want to use UTC_TIME_STAMP. Is there any plugin or any option to achieve this?
I understand there is lot of question in SO regarding UTC. But most of the accepted answers are wrong. It's also returns local time of the server but not UTC. Please help me to solve this problem. Thank you.
Code:
let utcString = new Date().toISOString();
let myTime = utcString.split('T')
let dates = myTime[0].split('-')
let times = myTime[1].split('.')
let time = times[0].split(':')
let ms = times[1].split('Z')[0]
var utcDate = Date.UTC(dates[0], dates[1], dates[2], time[0], time[1], time[2], ms); // It's returns UTC for local TIME_STAMP :( of the server. When I convert it to my time zone using `online tools`. It's future time.
return utcDate
CodePudding user response:
The static Date.now() method returns the number of milliseconds elapsed since January 1, 1970 00:00:00 UTC.
CodePudding user response:
Use Date.toUTCString()
:
const d = new Date().toUTCString();
console.log(d)