How do I get a UTC Timestamp in JavaScript?
While writing a web application, it makes sense to store (server side) all datetimes in the DB as UTC timestamps.
I was astonished when I noticed that you couldn't natively do much in terms of Timezone manipulation in JavaScript.
I extended the Date object a little. Does this function make sense? Basically, every time I send anything to the server, it's going to be a timestamp formatted with this function...
Can you see any major problems here? Or maybe a solution from a different angle?
Date.prototype.getUTCTime = function(){
return new Date(
this.getUTCFullYear(),
this.getUTCMonth(),
this.getUTCDate(),
this.getUTCHours(),
this.getUTCMinutes(),
this.getUTCSeconds()
).getTime();
}
It just seems a little convoluted to me. And I am not so sure about performance either.
Solution 1:
Dates constructed that way use the local timezone, making the constructed date incorrect. To set the timezone of a certain date object is to construct it from a date string that includes the timezone. (I had problems getting that to work in an older Android browser.)
Note that
getTime()
returns milliseconds, not plain seconds.
For a UTC/Unix timestamp, the following should suffice:
Math.floor((new Date()).getTime() / 1000)
It will factor the current timezone offset into the result. For a string representation, David Ellis' answer works.
To clarify:
new Date(Y, M, D, h, m, s)
That input is treated as local time. If UTC time is passed in, the results will differ. Observe (I'm in GMT +02:00 right now, and it's 07:50):
> var d1 = new Date();
> d1.toUTCString();
"Sun, 18 Mar 2012 05:50:34 GMT" // two hours less than my local time
> Math.floor(d1.getTime()/ 1000)
1332049834
> var d2 = new Date( d1.getUTCFullYear(), d1.getUTCMonth(), d1.getUTCDate(), d1.getUTCHours(), d1.getUTCMinutes(), d1.getUTCSeconds() );
> d2.toUTCString();
"Sun, 18 Mar 2012 03:50:34 GMT" // four hours less than my local time, and two hours less than the original time - because my GMT+2 input was interpreted as GMT+0!
> Math.floor(d2.getTime()/ 1000)
1332042634
Also note that getUTCDate()
cannot be substituted for getUTCDay()
. This is because getUTCDate()
returns the day of the month; whereas, getUTCDay()
returns the day of the week.
Solution 2:
The easiest way of getting UTC time in a conventional format is as follows:
> new Date().toISOString()
"2016-06-03T23:15:33.008Z"
if you need EPOC timestamp, pass your date to Date.parse method
> Date.parse(new Date)
1641241000000
> Date.parse('2022-01-03T20:18:05.833Z')
1641241085833
Or you can use + for type casting from Date to Int
> +new Date
1641921156671
EPOC timestamp in seconds.
> parseInt(Date.parse('2022-01-03T20:18:05.833Z') / 1000)
1641241085
Solution 3:
You could also do it utilizing getTimezoneOffset and getTime,
x = new Date()
var UTCseconds = (x.getTime() + x.getTimezoneOffset()*60*1000)/1000;
console.log("UTCseconds", UTCseconds)
Solution 4:
I actually think Date values in js are far better than say the C# DateTime objects. The C# DateTime objects have a Kind property, but no strict underlying time zone as such, and time zone conversions are difficult to track if you are converting between two non UTC and non local times. In js, all Date values have an underlying UTC value which is passed around and known regardless of the offest or time zone conversions that you do. My biggest complaint about the Date object is the amount of undefined behaviour that browser implementers have chosen to include, which can confuse people who attack dates in js with trial and error than reading the spec. Using something like iso8601.js solves this varying behaviour by defining a single implementation of the Date object.
By default, the spec says you can create dates with an extended ISO 8601 date format like
var someDate = new Date('2010-12-12T12:00Z');
So you can infer the exact UTC time this way.
When you want to pass the Date value back to the server you would call
someDate.toISOString();
or if you would rather work with a millisecond timestamp (number of milliseconds from the 1st January 1970 UTC)
someDate.getTime();
ISO 8601 is a standard. You can't be confused about what a date string means if you include the date offset. What this means for you as a developer is that you never have to deal with local time conversions yourself. The local time values exist purely for the benefit of the user, and date values by default display in their local time. All the local time manipulations allow you to display something sensible to the user and to convert strings from user input. It's good practice to convert to UTC as soon as you can, and the js Date object makes this fairly trivial.
On the downside there is not a lot of scope for forcing the time zone or locale for the client (that I am aware of), which can be annoying for website-specific settings, but I guess the reasoning behind this is that it's a user configuration that shouldn't be touched.
So, in short, the reason there isn't a lot of native support for time zone manipulation is because you simply don't want to be doing it.