I want to get the UTC time using moment.utc() as a date object instead of epoch or string (moment.utc().format() or using .toISOString()). moment.utc().toDate() returns my local time. Any help would be appreciated.
You can use moment().toDate(). If you coerce the date to a string (e.g. by sending it to the console, alert, etc.), the built-in (implementation dependent) toString method will typically use the host timezone settings to generate a string, e.g.
var m = moment().toDate(); // Equivalent to new Date()
console.log(m + '') // coerce to string uses built-in toString
console.log(m.toISOString()) // ISO 8601 string offset +0000
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.18.1/moment.min.js"></script>
Related
I have a string called stringDate that is equal to 2023-01-20T04:48:42.327000 which is a string. This is in UTC time. I live in the Pacific timezone so the following code should return 2023-01-19T20:48:42.327Z but it's returning 2023-01-20T12:48:42.327Z. Why is this happening?
let date: any = new Date(stringDate);
console.log(date);
To force new Date() to parse a date time object as UTC you can append a zero time zone offset to it.
let date: any = new Date(stringDate + '+00:00');
The issue is most likely due to the fact that JavaScript's Date object assumes that the input string is in local time, not UTC. This means that the Date object is automatically converting the input string to the local time zone.
So using .toISOString() method, which will return a string in ISO format, including the UTC offset (represented by 'Z' at the end):
let date: any = new Date(stringDate);
console.log(date.toISOString());
This will correctly parse the input string as UTC time and output the expected result 2023-01-19T20:48:42.327Z.
I wish to create a new Date in JS, but have it be cast as UTC time. For example, suppose castAsUTC() produces the following desired effect:
var x = new Date('2019-01-01T00:00:00') // In local time (PST)
castAsUTC(x).toISOString(); // => '2019-01-01T00:00:00Z'
// x.toISOString() gives us '2019-01-01T08:00:00Z', which is undesired
Currently, my function looks like this:
function castAsUTC(date) {
return new Date(x.toLocaleString() + '+00:00');
}
Is there a cleaner/nicer way of producing the same effect? Thanks in advance!
EDIT: To be more specific, I'm interested in transforming the date's timezone, without changing its actual value with as little arithmetic as possible. So calling .toISOString() will produce the same date as it is in local time.
I am currently using the moment-timezone library, but I can't seem to get the desired effect using that, either. I would definitely accept an answer that uses Moment.js
You can switch a Moment instance to UTC using the utc function. Then just use format to get whatever the specific output you want from it.
If indeed the string you have is like the one shown, then the easiest thing to do would be to append a Z to indicate UTC.
var input = '2019-01-01T00:00:00';
var date = new Date(input + 'Z');
var output = date.toISOString();
Or, if you would like to use Moment.js, then do this:
var input = '2019-01-01T00:00:00';
var m = moment.utc(input);
var output = m.format();
You do not need moment-timezone for this.
tl;dr;
You formatted the date wrong. Add the letter "Z" to the end of your date string and it will be treated as UTC.
var x = new Date('2019-01-01T00:00:00Z') // Jan 1, 2019 12 AM UTC
These formatting issues are easier to manage with a library like momentjs (utc and format functions) as described in other answers. If you want to use vanilla javascript, you'll need to subtract out the timezone offset before calling toISOString (see warnings in the longer answer below).
Details
Date in javascript deals with timezones in a somewhat counter intuitive way. Internally, the date is stored as the number of milliseconds since the Unix epoch (Jan 1, 1970). That's the number you get when you call getTime() and it's the number that's used for math and comparisons.
However - when you use the standard string formatting functions (toString, toTimeString, toDateString, etc) javascript automatically applies the timezone offset for the local computers timezone before formatting. In a browser, that means it will apply the offset for the end users computer, not the server. The toISOString and toUTCString functions will not apply the offset - they print the actual UTC value stored in the Date. This will probably still look "wrong" to you because it won't match the value you see in the console or when calling toString.
Here's where things really get interesting. You can create Date's in javascript by specifying the number of milliseconds since the Unix epoch using new Date(milliseconds) or by using a parser with either new Date(dateString). With the milliseconds method, there's no timezone to worry about - it's defined as UTC. The question is, with the parse method, how does javascript determine which timezone you intended? Before ES5 (released 2009) the answer was different depending on the browser! Post ES5, the answer depends on how you format the string! If you use a simplified version of ISO 8601 (with only the date, no time), javascript considers the date to be UTC. Otherwise, if you specify the time in ISO 8601 format, or you use a "human readable" format, it considers the date to be local timezone. Check out MDN for more.
Some examples. I've indicated for each if javascript treats it as a UTC or a local date. In UTC, the value would be Jan 1, 1970 at midnight. In local it depends on the timezone. For OP in pacfic time (UTC-8), the UTC value would be Jan 1, 1970 at 8 AM.
new Date(0) // UTC (milliseconds is always UTC)
new Date("1/1/1970"); // Local - (human readable string)
new Date("1970-1-1"); // Local (invalid ISO 8601 - missing leading zeros on the month and day)
new Date("1970-01-01"); // UTC (valid simplified ISO 8601)
new Date("1970-01-01T00:00"); // Local (valid ISO 8601 with time and no timezone)
new Date("1970-01-01T00:00Z"); // UTC (valid ISO 8601 with UTC specified)
You cannot change this behavior - but you can be pedantic about the formats you use to parse dates. In your case, the problem was you provided an ISO-8601 string with the time component but no timezone. Adding the letter "Z" to the end of your string, or removing the time would both work for you.
Or, always use a library like momentjs to avoid these complexities.
Vanilla JS Workaround
As discussed, the real issue here is knowing whether a date will be treated as local or UTC. You can't "cast" from local to UTC because all Date's are UTC already - it's just formatting. However, if you're sure a date was parsed as local and it should really be UTC, you can work around it by manually adjusting the timezone offset. This is referred to as "epoch shifting" (thanks #MattJohnson for the term!) and it's dangerous. You actually create a brand new Date that refers to a different point in time! If you use it in other parts of your code, you can end up with incorrect values!
Here's a sample epoch shift method (renamed from castAsUtc for clarity). First get the timezone offset from the object, then subtract it and create a new date with the new value. If you combine this with toISOString you'll get a date formatted as you wanted.
function epochShiftToUtc(date) {
var timezoneOffsetMinutes = date.getTimezoneOffset();
var timezoneOffsetMill = timezoneOffsetMinutes * 1000 * 60;
var buffer = new Date(date.getTime() - timezoneOffsetMill);
return buffer;
}
epochShiftToUtc(date).toUTCString();
console.log(new Date('2016-05-24').toISOString()); // '2016-05-24T00:00:00.000Z'
console.log(new Date('05/26/2016').toISOString()); // '2016-05-23T23:00:00.000Z' // why?
I am sending data to the server to parse and want to ensure that server will encode my date correctly.
What is the simplest way to convert date to string as '2016-05-24T00:00:00.000Z' in both cases?
Thanks
console.log(new Date('2016-05-24 GMT').toISOString()); // '2016-05-24T00:00:00.000Z'
console.log(new Date('05/24/2016 GMT').toISOString()); // '2016-05-24T00:00:00.000Z'
Append the timezone to the date before creating a new date object so that the string parsing code in the Date constructor doesn't get confused. Always disambiguate if possible.
Your code was using different timezones for each parse because of the way the dates were formatted. One was using +0 timezone, other was using -1 timezone hence the date being pulled back an hour when the ISO string was created.
One is parsing in UTC time, one is parsing in local time.
new Date('2016-05-24').toISOString() // '2016-05-24T00:00:00.000Z'
new Date('05/24/2016').toISOString() // '2016-05-24T07:00:00.000Z'
Playing around, here's one solution:
new Date(new Date('05/24/2016') - (new Date()).getTimezoneOffset() * 60000).toISOString() // '2016-05-24T00:00:00.000Z'
The strategy:
Create the new offset date
Subtract the offset
Create a new date from that result
Reference links:
javascript toISOString() ignores timezone offset
Why does Date.parse give incorrect results?
On further consideration, I'd recommend parsing the date string into something that is "universal" before passing it to the date constructor. Something like:
var tmp = ('05/24/2016').split('//');
var universal = [tmp[2], tmp[0], tmp[1]].join('-'); // 2016-05-24
...
Also, Moment.js does this sort of thing very neatly.
Use the getDate(), getMonth() and getFullYear() methods to strip out what you need.
I need to convert session.lastAccessedTime object from jsp into Javascript Date object. Currently, it displays as long object. How can I convert to Javascript date object?
console.log('MaxInactive Interval == ' + ${pageContext.session.lastAccessedTime});
You can use Date.parse() method to convert date string to date object.
MDN Date.parse()
The Date.parse() method parses a string representation of a date, and returns the number of milliseconds since January 1, 1970, 00:00:00 UTC
Date.parse(lastAccessedTime)
Is it possible in javascript to convert some date in timestamp ?
i have date in this format 2010-03-09 12:21:00 and i want to convert it into its equivalent time stamp with javascript.
In response to your edit:
You need to parse the date string to build a Date object, and then you can get the timestamp, for example:
function getTimestamp(str) {
var d = str.match(/\d+/g); // extract date parts
return +new Date(d[0], d[1] - 1, d[2], d[3], d[4], d[5]); // build Date object
}
getTimestamp("2010-03-09 12:21:00"); // 1268158860000
In the above function I use a simple regular expression to extract the digits, then I build a new Date object using the Date constructor with that parts (Note: The Date object handles months as 0 based numbers, e.g. 0-Jan, 1-Feb, ..., 11-Dec).
Then I use the unary plus operator to get the timestamp.
Note also that the timestamp is expressed in milliseconds.
+(new Date())
Does the job.
The getTime() method of Date object instances returns the number of milliseconds since the epoch; that's a pretty good timestamp.