I had the same issue. I get a date as a String, for example: '2016-08-25T00:00:00', but I need to have the Date object with correct time. To convert String into object, I use getTimezoneOffset:
var date = new Date('2016-08-25T00:00:00')
var userTimezoneOffset = date.getTimezoneOffset() * 60000;
new Date(date.getTime() + userTimezoneOffset);
getTimezoneOffset() will return ether negative or positive value. This must be subtracted to work in every location in world.
I had the same issue. I get a date as a String, for example: '2016-08-25T00:00:00', but I need to have the Date object with correct time. To convert String into object, I use getTimezoneOffset:
var date = new Date('2016-08-25T00:00:00')
var userTimezoneOffset = date.getTimezoneOffset() * 60000;
new Date(date.getTime() + userTimezoneOffset);
getTimezoneOffset() will return ether negative or positive value. This must be subtracted to work in every location in world.
The date is parsed correctly, it's just toString that displays the timestamp in your local timezone:
let s = "2005-07-08T11:22:33+0000";
let d = new Date(Date.parse(s));
// this logs for me
// "Fri Jul 08 2005 13:22:33 GMT+0200 (Central European Summer Time)"
// and something else for you
console.log(d.toString())
// this logs
// Fri, 08 Jul 2005 11:22:33 GMT
// for everyone
console.log(d.toUTCString())
Javascript Date object are time values - they merely contain a number of milliseconds since the epoch. There is no timezone info in a Date object. Which calendar date (day, minutes, seconds) this timestamp represents is a matter of the interpretation (one of to...String methods).
The above example shows that the date is being parsed correctly for offset +0000 - that is, it actually contains an amount of milliseconds corresponding to "2005-07-08T11:22:33" in GMT.
timezone - How do I get a UTC Timestamp in JavaScript? - Stack Overflow
javascript - Get a UTC timestamp - Stack Overflow
How to REALLY get a UTC Date object
var date = new Date('2015-10-11T14:03:19.243Z'); var str = date.toISOString();
More on reddit.comJavaScript - Parse UTC Date - Stack Overflow
Simple and stupid
var date = new Date();
var now_utc = Date.UTC(date.getUTCFullYear(), date.getUTCMonth(),
date.getUTCDate(), date.getUTCHours(),
date.getUTCMinutes(), date.getUTCSeconds());
console.log(new Date(now_utc));
console.log(date.toISOString());
The
toISOString()method returns a string in simplified extended ISO format (ISO 8601), which is always 24 or 27 characters long (YYYY-MM-DDTHH:mm:ss.sssZor±YYYYYY-MM-DDTHH:mm:ss.sssZ, respectively). The timezone is always zero UTC offset, as denoted by the suffix "Z".
Source: MDN web docs
The format you need is created with the .toISOString() method. For older browsers (ie8 and under), which don't natively support this method, the shim can be found here:
This will give you the ability to do what you need:
var isoDateString = new Date().toISOString();
console.log(isoDateString);
For Timezone work, moment.js and moment.js timezone are really invaluable tools...especially for navigating timezones between client and server javascript.
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.
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
> parseInt(new Date / 1000)
1643302523
const timestamp = new Date().getTime()
console.log(timestamp)
For more information, see @James McMahon's answer.
As wizzard pointed out, the correct method is,
new Date().getTime();
or under Javascript 1.5, just
Date.now();
From the documentation,
The value returned by the getTime method is the number of milliseconds since 1 January 1970 00:00:00 UTC.
If you wanted to make a time stamp without milliseconds you can use,
Math.floor(Date.now() / 1000);
I wanted to make this an answer so the correct method is more visible.
You can compare ExpExc's and Narendra Yadala's results to the method above at http://jsfiddle.net/JamesFM/bxEJd/, and verify with http://www.unixtimestamp.com/ or by running date +%s on a Unix terminal.
I have a timestamp (e.g. 2015-10-11T14:03:19.243) and I need to get a UTC (timezone agnostic) Date object from javascript so I can use the strftime library. I have been having a hell of a time with this and I have no idea why nothing is working. Whenever I create a new Date with that timestamp I get that time in my browsers timezone...
Typically I would just use Moment.js for this but since it's relatively large I can't as I need to keep this app as lightweight as possible
var date = new Date('2015-10-11T14:03:19.243Z'); var str = date.toISOString();
I need to get a UTC (timezone agnostic) Date object from javascript
There's no such thing. A JS date object is ALWAYS in the local timezone. The best you could do is something like:
tmp = new Date('2015-10-11T14:03:19.243Z')
date = date = {
year: tmp.getUTCFullYear(),
month: tmp.getUTCMonth(),
day: tmp.getUTCDate(),
hours: tmp.getUTCHours(),
minutes: tmp.getUTCMinutes(),
seconds: tmp.getUTCSeconds()
}
/* And then do whatevery you want with your new date object*/
dateString = date.year+'/'+date.month+'/'+date.day;
timeString = date.hours+':'+date.minutes+':'+date.seconds;
console.log('Hi, the date is ' + dateString + ' and the time is ' + timeString + '.');
And you could build out some parametrized functions and helper methods and such, and it wouldn't be toooo bad. But it'll never be great. There's a reason moment.js is used everywhere; JS date handling is terrifyingly bad.
You can also use .toUTCString() or .toISOString(), but I don't think that solves your stated problem.
You can do append 'T00:00:00.000Z' to make the time zone specific (Z indicates UTC)
new Date('2015-08-27' + 'T00:00:00.000Z')
Note that new Date('2015-08-27') is treated differently in ES5 (UTC) vs. ES6 (Local), so you can't expect it any correction to be work consistently if you were planning to to hard code it (i.e. don't do it)
Also, do note that your console.log might show you the local time corresponding to the UTC time the expression evaluates to (that tends to throw you off a bit if you are expecting UTC to be at the end for expression that evaluate to UTC times and your local time zone at the end for those that evaluate to your local time). For instance
new Date('2015-08-27T00:00:00.000Z')
could show
Thu Aug 27 2015 1:00:00 GMT+100
which is the same as
Thu Aug 27 2015 00:00:00 UTC
In some cases, when other solutions don't work, adding GMT will help:
new Date('July 11, 2022, 16:22:14 PM' + ' GMT')
(note, an user below in comment, reports bug about this)