user1229351
user1229351

Reputation: 2035

javascript get timestamp in system timezone not in UTC

Hi all im looking for a way to get current system time in a timestamp. i used this to get timestamp:

new Date().getTime();

but it return the time in UTC timezone not the timezone that server use

is there any way to get timestamp with system timezone?

Upvotes: 17

Views: 46171

Answers (3)

Nilisha Maheshwari
Nilisha Maheshwari

Reputation: 71

Install the module 'moment' using:

npm install moment --save

And then in the code add the following lines -

var moment = require('moment');
var time = moment();
var time_format = time.format('YYYY-MM-DD HH:mm:ss Z');
console.log(time_format);

Upvotes: 7

ScottyC
ScottyC

Reputation: 1547

Since getTime returns unformatted time in milliseconds since EPOCH, it's not supposed to be converted to time zones. Assuming you're looking for formatted output,

Here is a stock solution without external libraries, from an answer to a similar question:

the various toLocale…String methods will provide localized output.

d = new Date();
alert(d);                        // -> Sat Feb 28 2004 23:45:26 GMT-0300 (BRT)
alert(d.toLocaleString());       // -> Sat Feb 28 23:45:26 2004
alert(d.toLocaleDateString());   // -> 02/28/2004
alert(d.toLocaleTimeString());   // -> 23:45:26

And extra formatting options can be provided if needed.

Upvotes: 9

Noah
Noah

Reputation: 34303

Check out moment.js http://momentjs.com/

npm install -S moment

New moment objects will by default have the system timezone offset.

var now = moment()
var formatted = now.format('YYYY-MM-DD HH:mm:ss Z')
console.log(formatted)

Upvotes: 19

Related Questions