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.
This question is related to
javascript
timezone
utc
I use the following:
Date.prototype.getUTCTime = function(){
return this.getTime()-(this.getTimezoneOffset()*60000);
};
Once defined this method you can do:
var utcTime = new Date().getUTCTime();
You generally don't need to do much of "Timezone manipulation" on the client side. As a rule I try to store and work with UTC dates, in the form of ticks
or "number of milliseconds since midnight of January 1, 1970." This really simplifies storage, sorting, calculation of offsets, and most of all, rids you of the headache of the "Daylight Saving Time" adjustments. Here's a little JavaScript code that I use.
To get the current UTC time:
function getCurrentTimeUTC()
{
//RETURN:
// = number of milliseconds between current UTC time and midnight of January 1, 1970
var tmLoc = new Date();
//The offset is in minutes -- convert it to ms
return tmLoc.getTime() + tmLoc.getTimezoneOffset() * 60000;
}
Then what you'd generally need is to format date/time for the end-user for their local timezone and format. The following takes care of all the complexities of date and time formats on the client computer:
function formatDateTimeFromTicks(nTicks)
{
//'nTicks' = number of milliseconds since midnight of January 1, 1970
//RETURN:
// = Formatted date/time
return new Date(nTicks).toLocaleString();
}
function formatDateFromTicks(nTicks)
{
//'nTicks' = number of milliseconds since midnight of January 1, 1970
//RETURN:
// = Formatted date
return new Date(nTicks).toLocaleDateString();
}
function formatTimeFromTicks(nTicks)
{
//'nTicks' = number of milliseconds since midnight of January 1, 1970
//RETURN:
// = Formatted time
return new Date(nTicks).toLocaleTimeString();
}
So the following example:
var ticks = getCurrentTimeUTC(); //Or get it from the server
var __s = "ticks=" + ticks +
", DateTime=" + formatDateTimeFromTicks(ticks) +
", Date=" + formatDateFromTicks(ticks) +
", Time=" + formatTimeFromTicks(ticks);
document.write("<span>" + __s + "</span>");
Returns the following (for my U.S. English locale):
ticks=1409103400661, DateTime=8/26/2014 6:36:40 PM, Date=8/26/2014, Time=6:36:40 PM
I think this what you are expecting...
var currTimestamp = Date.now(), //1482905176396
utcDateString = (new Date(currTimestamp)).toUTCString(); //"Wed, 28 Dec 2016 06:06:50 GMT"
Now,
new Date(utcDateString).getTime(); //This will give you UTC Timestamp in JavaScript
The easiest way of getting UTC time in a conventional format is as follows:
new Date().toISOString()
"2016-06-03T23:15:33.008Z"
EDIT: The code below does NOT work. I was always assuming that new Date().getTime() returned the number of seconds since the 1st of January 1970 IN THE CURRENT TIMEZONE. This is not the case: getTime() returns the number of seconds in UTC. So, the code below does gross over-adjusting. Thank you everybody!]
First of all, thank you for your fantastic insights. I guess my question had the wrong title... it should have been "Get the UTC Unix Timestamp for an existing date".
So, if I have a date object:
var d = new Date(2009,01,31)
I was after a function that would tell me "The UTC Unix Timestamp".
This function seems to be the real trick:
Date.prototype.getUTCUnixTime = function (){
return Math.floor( new Date(
this.getUTCFullYear(),
this.getUTCMonth(),
this.getUTCDate(),
this.getUTCHours(),
this.getUTCMinutes(),
this.getUTCSeconds()
).getTime() / 1000);
}
Note that it works on "this" This means that I can do:
var n = new Date(2008,10,10)
...
...
n.getUTCUnixTime();
And get the number of seconds since the 1st of Jan 1970 in Unix time. Right?
It's a little insane, to me, that Javascript stores everything in UTC times, but then in order to get that number I have to create a new Date object passing the individual UTC getters and then finally call getTime() for that...
Merc.
You could also do it utilizing getTimezoneOffset and getTime,
x = new Date()_x000D_
var UTCseconds = (x.getTime() + x.getTimezoneOffset()*60*1000)/1000;_x000D_
_x000D_
console.log("UTCseconds", UTCseconds)
_x000D_
I think this is a better solution
// UTC milliseconds
new Date(Date.now()+(new Date().getTimezoneOffset()*60000)).getTime()
// UTC seconds
new Date(Date.now()+(new Date().getTimezoneOffset()*60000)).getTime()/1000|0
I want to make clear that new Date().getTime() does in fact return a UTC value, so it is a really helpful way to store and manage dates in a way that is agnostic to localized times.
In other words, don't bother with all the UTC javascript functions. Instead, just use Date.getTime().
More info on the explanation is here: If javascript "(new Date()).getTime()" is run from 2 different Timezones.
This will return the timestamp in UTC:
var utc = new Date(new Date().toUTCString()).getTime();
_x000D_
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.
Since new Date().toUTCString()
returns a string like "Wed, 11 Oct 2017 09:24:41 GMT"
you can slice the last 3 characters and pass the sliced string to new Date()
:
new Date()
// Wed Oct 11 2017 11:34:33 GMT+0200 (CEST)
new Date(new Date().toUTCString().slice(0, -3))
// Wed Oct 11 2017 09:34:33 GMT+0200 (CEST)
Using day.js
In browser:
dayjs.extend(dayjs_plugin_utc)
console.log(dayjs.utc().unix())
_x000D_
<script src="https://cdn.jsdelivr.net/npm/dayjs@latest/dayjs.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/dayjs@latest/plugin/utc.js"></script>
_x000D_
In node.js:
import dayjs from 'dayjs'
dayjs.extend(require('dayjs/plugin/utc'))
console.log(dayjs.utc().unix())
You get a UTC unix timestamp without milliseconds.
I am amazed at how complex this question has become.
These are all identical, and their integer values all === EPOCH time :D
console.log((new Date()).getTime() / 1000, new Date().valueOf() / 1000, (new Date() - new Date().getTimezoneOffset() * 60 * 1000) / 1000);
Do not believe me, checkout: http://www.epochconverter.com/
Once you do this
new Date(dateString).getTime() / 1000
It is already UTC time stamp
const getUnixTimeUtc = (dateString = new Date()) => Math.round(new Date(dateString).getTime() / 1000)
I tested on https://www.unixtimestamp.com/index.php
If you want a one liner, The UTC Unix Timestamp can be created in JavaScript as:
var currentUnixTimestap = ~~(+new Date() / 1000);
This will take in account the timezone of the system. It is basically time elapsed in Seconds since epoch.
new Date()
.unary +
before object creation to convert it to timestamp integer
. : +new Date()
.+new Date() / 1000
~~(+new Date())
Source: Stackoverflow.com