Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 968
user1229351 Avatar asked May 06 '13 06:05

user1229351


People also ask

Is JavaScript date always UTC?

The JavaScript Date is always stored as UTC, and most of the native methods automatically localize the result.

How do I get a UTC timestamp in JavaScript?

Use the getTime() method to get a UTC timestamp, e.g. new Date(). getTime() . The method returns the number of milliseconds since the Unix Epoch and always uses UTC for time representation.

Is timestamp stored in UTC?

Internally, the timestamp is as an integer, representing seconds in UTC since the epoch ( 1970-01-01 00:00:00 UTC ) and TIMESTAMPTZ values also stored as integers with respect to Coordinated Universal Time (UTC).

How do I get a specific timezone offset?

The JavaScript getTimezoneOffset() method is used to find the timezone offset. It returns the timezone difference in minutes, between the UTC and the current local time. If the returned value is positive, local timezone is behind the UTC and if it is negative, the local timezone if ahead of UTC.


2 Answers

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)
like image 79
Noah Avatar answered Sep 18 '22 23:09

Noah


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.

  • toLocaleString
  • Various other Date functions you may want to use
like image 44
ScottyC Avatar answered Sep 20 '22 23:09

ScottyC