How to parse to Date from String value like '20180131T120000Z'? - javascript

I am trying to parse the String date format(yyyyMMddThhmmssZ) to Date.
const date = Date.parse("20171201T120000Z");
console.log(date );
Result is ...
NaN
Could you teach me the smartest way?

Ideally, you should try to standardize the date string in a way that works best for your needs. As the MDN states, parsing a date from a string is problematic in general.
Date.parse()
Note: Parsing of strings with Date.parse is strongly discouraged due to browser differences and inconsistencies.
Although your date format is valid ISO 8601 as illustrated in the comments by #duskwuff, it is not supported by Date.parse.
It seems the version specified here by ECMAScript is supported, YYYY-MM-DDTHH:mm:ss.sssZ, but not a format like 20180131T011614Z as you are using. It seems Date.parse only supports a simplification of the ISO 8601 format.
A library like moment.js is helpful as it can parse a wide range of date formats automatically (including your valid ISO 8601 date) or you can even specify your date format explicitly if you wanted.
moment('20171201T120000Z', 'YYYYMMDDTHHmmssZ').toString()
"Fri Dec 01 2017 06:00:00 GMT-0600"
moment('20171201T120000Z').toString()
"Fri Dec 01 2017 06:00:00 GMT-0600"
Though, for your example, you could parse out the date without moment.js
let dateString = '20171201T120000Z'
let [_, year, month, day, hour, min, sec] = dateString.match(/(\d{4})(\d{2})(\d{2})T(\d{2})(\d{2})(\d{2})/)
// month is 0-based so subtract 1
new Date(year, month - 1, day, hour, min, sec)
Could you teach me the smartest way?
I would say the "smartest way" can vary wildly based on your circumstances.
Do you control the source of these date strings?
Are the date strings coming from another system?
Are users entering these date strings?
As long as you use some standard (even if it's not supported directly by Date.parse), then I would say the parsing can be done with whatever method works best for you. A library like moment, manually parsing the elements of the date, translating your date to epoch or a format recognized by Date.parse, or whatever you prefer.

Related

Alternative to casting UTC Date in Javascript?

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();

Initialize JS date object from HTML date picker: incorrect date returned

How do you correctly intitialize a timezone-independent date (or I guess a date that is fixed to a single timezone across the html side and the JS side) from a html datepicker?
I have the following simple code, which is producing incorrect dates:
function printDate(){
let d = new Date(document.getElementById("date").value)
alert(d)
}
document.getElementById("printDate").addEventListener("click", e => printDate())
<html>
<body>
Print Date: <br><input type="date" id="date"> <button id="printDate">Add</button>
</body>
</html>
But at least on my computer, currently sitting in U.S. mountain time, it produces incorrect dates. I give it today's date (March 9, 2019), and it alerts yesterday's date in the following format: Fri Mar 08 2019 17:00:00 GMT-0700 (MST). How do I make it not do that?
I really just want it to assume that all input and all output are in GMT.
In a <input type="date" /> element, the selected date is displayed in the locale format, but the value property is always returned in yyyy-mm-dd format, as described in the MDN docs.
In other words, when you choose March 9, 2019, you may see 03/09/2019 from the US or 09/03/2019 in other parts of the world, but value is 2019-03-09 regardless of any time zone or localization settings. This is a good thing, as it allows you to work with the selected date in a standard ISO 8601 format, without trying to apply a time.
However, when you parse a date string in that format with the Date object's constructor (or with Date.parse), you run up against a known issue: The date is not treated as local time, but as UTC. This is the opposite of ISO 8601.
This is described in the MDN docs:
Note: parsing of date strings with the Date constructor (and Date.parse, they are equivalent) is strongly discouraged due to browser differences and inconsistencies. Support for RFC 2822 format strings is by convention only. Support for ISO 8601 formats differs in that date-only strings (e.g. "1970-01-01") are treated as UTC, not local.
It's also in the ECMAScript specification (emphasis mine):
... When the time zone offset is absent, date-only forms are interpreted as a UTC time and date-time forms are interpreted as a local time.
There was a debate about this in 2015, but ultimately it was decided that maintaining compatibility with existing behaviors was more important than being ISO 8601 compliant.
Going back to your question, the best thing to do would be to not parse it into a Date object if you don't need one. In other words:
function printDate(){
const d = document.getElementById("date").value;
alert(d);
}
If you really need a Date object, then the easiest option is to parse the value yourself:
function printDate(){
const parts = document.getElementById("date").value.split('-');
const d = new Date(+parts[0], parts[1]-1, +parts[2], 12);
alert(d);
}
Note the ,12 at the end sets the time to noon instead of midnight. This is optional, but it avoids situations of getting the wrong day when midnight doesn't exist in the local time zone where DST transitions at midnight (Brazil, Cuba, etc.).
Then there's your last comment:
I really just want it to assume that all input and all output are in GMT.
That's a bit different than what you showed. If really that's what you want, then you can construct the Date object as you previously did, and use .toISOString(), .toGMTString(), or .toLocaleString(undefined, {timeZone: 'UTC'})
function printDate(){
const d = new Date(document.getElementById("date").value); // will treat input as UTC
// will output as UTC in ISO 8601 format
alert(d.toISOString());
// will output as UTC in an implementation dependent format
alert(d.toGMTString());
// will output as UTC in a locale specific format
alert(d.toLocaleString(undefined, {timeZone: 'UTC'}));
}

How to force Moment.js to prioritize day before month when parsing ambiguous dates?

Is there a way to force Moment.js to always assume that the day comes before the month in ambiguous situations?
For example:
moment("10-05-2018") should be 10 May 2018
moment("06/08/2018") should be 06 August 2018
moment("01 03 2018") should be 01 March 2018
Simply use moment(String, String), where DD is day of month, MM is month number and YYYY is 4 or 2 digit year.
Please note that since your input is neither in a recognized ISO 8601 nor RFC 2822 format, you should use moment(String, String) over moment(String) to get consistent results across browsers.
When creating a moment from a string, we first check if the string matches known ISO 8601 formats, we then check if the string matches the RFC 2822 Date time format before dropping to the fall back of new Date(string) if a known format is not found.
Warning: Browser support for parsing strings is inconsistent. Because there is no specification on which formats should be supported, what works in some browsers will not work in other browsers.
For consistent results parsing anything other than ISO 8601 strings, you should use String + Format.
Here a live sample
["10-05-2018","06/08/2018", "01 03 2018"].forEach( (item) => {
console.log( moment(item, 'DD MM YYYY').format() );
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.24.0/moment.min.js"></script>

How can I create a Date from string, ignoring any timezone offsets?

The server uses +03:00 timezone. It offers me a date in this format: "2017-04-12T00:00:00+03:00"
I then create a new Date from this string:
options.startDate = new Date("2017-04-12T00:00:00+03:00")
But because on the client there is a different timezone, the result is actually:
Tue Apr 11 2017 23:00:00 GMT+0200 (Central Europe Daylight Time)
This brings me back one day and it's a big deal for me. Is there an elegant way to avoid this and create the same Date and Time in javascript, ignoring the timezone offset?
The date you have in options.startDate is the correct one. What you want is to display it as if you were from the same timezone as the server.
If you now server's timezone in the client script then I would considere using a library like moment.js. It would allow you to format date in the timezone you want (GMT for instance, or the one of the server).
Using both moment.js and its plugin timezone code could be :
moment("2017-04-12T00:00:00+03:00").tz("America/Los_Angeles").format();
You should never use the Date constructor or Date.parse to parse strings due to browsers differences. Even if you remove the timezone from the string and parse the remainder, e.g.
console.log( new Date('2017-04-12T00:00:00+03:00'.substr(0,19)).toString() );
you'll get different results in different browsers (e.g. Firefox and Safari).
If you don't want to use a library, use a simple function (see below). However, if you remove the timezone, the string will represent a different moment in time in each timezone with a different offset.
function parseISOIgnoreTimezone(s) {
var b = s.split(/\D/);
return new Date(b[0], b[1]-1, b[2], b[3], b[4], b[5]);
}
console.log(parseISOIgnoreTimezone('2017-04-12T00:00:00+03:00').toString());
I really recommend #VictorDrouin his answer.
But if for some reason you don't want moment.js or fiddle around with it you can use this 'hack'
new Date("2017-04-12T00:00:00+03:00".match(/\d{4}\-\d{2}\-\d{2}T\d{2}:\d{2}:\d{2}/).pop());
What it does it matches the date against given regex date format, and then supplies it to the date parser which makes it a date.
Be careful when supplying it back to the database that you supply it back without timezone offset.
var stringdate = "2017-04-12T00:00:00+03:00";
function getDate(str_date) {
var matched = str_date.match(/\d{4}\-\d{2}\-\d{2}T\d{2}:\d{2}:\d{2}/).pop();
return new Date(matched);
}
console.log(getDate(stringdate));

Convert ISO Date string to date in JavaScript

Need help to convert exactly from ISO Date string to Date:
I have an ISO string date: "2016-01-23T22:23:32.927".
But when I use new Date(dateString) to convert Date, the result is wrong:
var date = new Date("2016-01-23T22:23:32.927");
The result is: Sun Jan 24 2016 05:23:32 GMT+0700. It's not true. I want the date is 23 not 24.
Please help me. Thanks a lot!
You need to supply a timezone offset with your iso date. Since there isn't one, it assumes the date to be in GMT and when you log it out, it prints it in the timezone of your browser. I think that if you pass "2016-01-23T22:23:32.927+07:00" to new Date() you would get the value you are expecting.
JavaScript environments (browser, node,...) use a single timezone for formatting dates as strings. Usually this is your system's timezone. Based on the output you get, yours is GMT+0700.
So what happened:
The string you passed as ISO format to the Date constructor doesn't specify a timezone. In this case it is treated as UTC.
When you then output the date (I'll assume with console.log), it is converted to the timezone of your environment. In this case 7 hours where added.
If that doesn't suit you, you can change the way you output the date. This depends on what output you want, e.g.:
If you just want the UTC timezone again, you can use date.toISOString().
If you want to output it in another timezone, you can call date.getTimezoneOffset() and figure out the difference between both timezones. You'd then probably need to get the individual date parts and add/subtract the timezone difference accordingly. At this point you could consider using an existing library, taking into account their possible disadvantages.
If you're willing and able to add a dependency, I recommend using moment.js for this. It makes date handling in Javascript much more straightforward and a lot safer, and fixes your specific problem right out of the box.
To do this, 1st load it from a CDN, e.g. Moment.JS 2.14.1 minified. Then use it as follows:
var date = moment("2016-01-23T22:23:32.927");
console.log(date);
// output: Sat Jan 23 2016 22:23:32 GMT-0500
...i.e. your desired result :)
Here's a jsfiddle demonstrating this.
Use date.toUTCString()
it'll give you 23 instead of 24 as it Convert a date object to a string, according to universal time

Categories

Resources