I know when constructing a Date object in JavaScript with a dateString parameter, the string must be something that parse() can recognize.
What date format can parse recognize?
For example:
var postDate = new Date("2011-03-08T23:52:38");
works in Chrome and Internet Explorer, but fails on an iPhone (returns Jan 1, 1970).
I cannot find any formal documentation on the .parse() method, or the constructor, about what the parameter should be.
The format yyyy-mm-ddThh:nn:ss doesn't work. What is the allowed format string?
The MDC documentation of Date.parse() states (quoting) :
It accepts the IETF standard (RFC
1123 Section 5.2.14 and elsewhere)
date syntax: "Mon, 25 Dec 1995 13:30:00 GMT".
OP Edit:
.NET syntax to create this datetime string:
/*
* r (RFC1123Pattern)
* ddd, dd MMM yyyy HH':'mm':'ss 'GMT'
* Mon, 15 Jun 2009 20:45:30 GMT
*/
dateTime.ToUniversalTime().ToString("r", CultureInfo.InvariantCulture); //"r" = RFC1123Pattern
Edit: The r (RFC1123 pattern) always appends "GMT", even though the time isn't GMT (it's local). You need to call .ToUniversalTime() first, in order to have the time actually be GMT.
Using the format that is produced by Date's toJSON method will work. This is the same as the toISOString method.
The date format is YYYY-MM-DDTHH:mm:ss.sssZ
Note: The time zone is always UTC as denoted by the suffix "Z".
var d = new Date();
console.log(d.toJSON());
console.log(d.toJSON() === d.toISOString());
console.log(Date.parse(d.toJSON()) === Date.parse(d.toISOString()));
You may find that the date shown isn't the same as on your clock; remember the time zone is UTC.
References:
Date.prototype.toJSON()
Date.prototype.toISOString()
Related
Doing this with the date-functions.js library (used e.g. in datetimepicker jQuery plugin):
Date.parseDate('2018-03-10 12:12', 'Y-m-d H:i')
gives:
Sat Mar 10 2018 12:12:00 GMT+0100 (Paris, Madrid)
How to get the result as Unix timestamp or GMT / UTC time instead?
A string like '2018-03-10 12:12' will usually be parsed as local as there is no timezone offset. It's also not ISO 8601 compliant so using the built-in parser will yield different results in different browsers.
While you can use a library, to parse it as UTC and get the time value is just 2 lines of code:
function toUTCTimeValue(s) {
var b = s.split(/\D/);
return Date.UTC(b[0],b[1]-1,b[2],b[3],b[4]);
}
// As time value
console.log(toUTCTimeValue('2018-03-10 12:12'));
// Convert to Date object and print as timestamp
console.log(new Date(toUTCTimeValue('2018-03-10 12:12')).toISOString());
var date = new Date('2018-03-10 12:12'.replace(' ', 'T'));
// Unix
console.log(Math.floor(date.getTime() / 1000));
// UTC
console.log(date.toUTCString());
As always, please have a look at the documentation at MDN: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date
Use MomentJS instead. You can specify exactly what format the string you're parsing is in. MomentJS can then provide you with the underlying Date object, unix timestamp as well as convert to UTC.
var d = moment('2018-03-10 12:12', 'YYYY-MM-DD HH:mm');
console.log(d.toDate());
console.log(d.unix());
console.log(d.utc().toDate());
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.21.0/moment.min.js"></script>
You could of course also parse the date as UTC too instead of treating it as a local time.
moment.utc('2018-03-10 12:12', 'YYYY-MM-DD HH:mm');
NOTE Bit difficult for me to test UTC as I'm in the UK and GMT and UTC are virtually the same.
I'm using the following code to get current date and time in nodejs.
var date = (new Date()).toJSON();
after converting to JSON, it returns a wrong time with a wrong timezone as below:
2018-01-03T11:16:38.773Z
but without toJSON() it returns the real time in correct timezone
Wed Jan 03 2018 14:47:12 GMT+0330 (Iran Standard Time)
The format is different because:
The toJSON method is a built-in member of the Date JavaScript object.
It returns an ISO-formatted date string for the UTC time zone (denoted
by the suffix Z).
What you can do:
You can override the toJSON method for the Date type, or define a
toJSON method for other object types to achieve transformation of data
for the specific object type before JSON serialization.
source
If you want the same result you could just use toString instead of toJSON:
var date = new Date().toString();
2018-01-03T11:17:12.000Z === Wed Jan 03 2018 14:47:12 GMT+0330 (Iran Standard Time)
The one on the left hand side is ISO timezone and one on the right is basically the browser timezone.
(new Date()).toJSON() converts into ISO timezone
So a simple way to convert to string is
var date = (new Date()).toString();
I have this problem.
I have this date with this format
var datestring = "2017-10-30T15:03:10.933044Z";
If I write my code like this
var d = new Date(datestring);
I obtaine
Mon Oct 30 2017 16:03:10 GMT+0100 (ora solare Europa occidentale)
because there is one hour of a daylight in italy now. Nevertheless, I would like to have the same hour of 'datestring' (15, and not 16).
Could you help me?
thank you very much
According to ECMA-262, if you want to treat an ISO 8601 format UTC timestamp as local, just remove the Z. However, it will now represent a different moment in time if the local timezone is not GMT+0000.
Also, using the built-in parser is not recommended (see Why does Date.parse give incorrect results?), as some browsers will still treat it as UTC (e.g. Safari 11) or perhaps invalid. You should either write your own function to parse the string, or use a library. There are plenty of good parsing and formatting libraries available.
var s = '2017-10-30T15:03:10.933044Z';
var d = new Date(s.replace(/z/i,''));
console.log(d.toString());
Your input string is in ISO-8601 format. In this format, the Z at the end means the timestamp is UTC-based.
You can obtain a more human-friendly UTC-based string representation with the .toUTCString() method.
var datestring = "2017-10-30T15:03:10.933044Z";
var d = new Date(datestring);
var s = d.toUTCString();
console.log(s) // "Mon, 30 Oct 2017 15:03:10 GMT"
If you want the string in a specific format, then consider using a library like Moment.js.
I am trying to convert datetime value from this format Wed Mar 9 09:48:09 PST 2016 into the following format YYYY-MM-DD HH:mm:ss
I tried to use moment but it is giving me a warning.
"Deprecation warning: moment construction falls back to js Date. This is discouraged and will be removed in upcoming major release. Please refer to https://github.com/moment/moment/issues/1407 for more info.
Arguments: [object Object]
fa/<#http://localhost:1820/Resources/Scripts/Plugins/moment.min.js:7:9493
ia#http://localhost:1820/Resources/Scripts/Plugins/moment.min.js:7:10363
Ca#http://localhost:1820/Resources/Scripts/Plugins/moment.min.js:7:15185
Ba#http://localhost:1820/Resources/Scripts/Plugins/moment.min.js:7:15024
Aa#http://localhost:1820/Resources/Scripts/Plugins/moment.min.js:7:14677
Da#http://localhost:1820/Resources/Scripts/Plugins/moment.min.js:7:15569
Ea#http://localhost:1820/Resources/Scripts/Plugins/moment.min.js:7:15610
a#http://localhost:1820/Resources/Scripts/Plugins/moment.min.js:7:41
#http://localhost:1820/Home/Test:89:29
jQuery.event.dispatch#http://localhost:1820/Resources/Scripts/Jquery/jquery.min.js:5225:16
jQuery.event.add/elemData.handle#http://localhost:1820/Resources/Scripts/Jquery/jquery.min.js:4878:6
"
according to https://github.com/moment/moment/issues/1407 I should not be trying to use moment() to do this since it is not reliable.
How can I reliably convert the Wed Mar 9 09:48:09 PST 2016 into the following format YYYY-MM-DD HH:mm:ss?
You could try using Date.toJSON() , String.prototype.replace() , trim()
var date = new Date("Wed Mar 9 09:48:09 PST 2016").toJSON()
.replace(/(T)|(\..+$)/g, function(match, p1, p2) {
return match === p1 ? " " : ""
});
console.log(date);
Since you tagged your question with moment, I'll answer using moment.
First, the deprecation is because you are parsing a date string without supplying a format specification, and the string is not one of the standard ISO 8601 formats that moment can recognize directly. Use a format specifier and it will work just fine.
var m = moment("Wed Mar 9 09:48:09 PST 2016","ddd MMM D HH:mm:ss zz YYYY");
var s = m.format("YYYY-MM-DD HH:mm:ss"); // "2016-03-09 09:48:09"
Secondly, recognize that in the above code, zz is just a placeholder. Moment does not actually interpret time zone abbreviations because there are just too many ambiguities ("CST" has 5 different meanings). If you needed to interpret this as -08:00, then you'd have to do some string replacements on your own.
Fortunately, it would appear (at least from what you asked) that you don't want any time zone conversions at all, and thus the above code will do the job.
I have a string "2014-01-27". Now how can it be converted into "2014-01-27T00:00:00.0000000" ?
Is that a valid date format avail in javascript ?
"2014-01-27T00:00:00.0000000" ? Is that a valid date format avail in javascript ?
Yes, but…
ECMA-262 says that where an ISO 8601-like string is missing the time zone (e.g. 2014-01-27T00:00:00.0000000) then it is assumed to be UTC. However, if you pass a string like that to Date.parse, some browsers treat it as local and some as UTC (and some, like IE 8, won't parse it at all, even with a time zone).
To avoid that, manually parse the string and create a UTC date:
function parseYMDasUTC(s) {
var b = s.split(/\D/);
return new Date(Date.UTC(b[0],--b[1],b[2]));
}
console.log(parseYMDasUTC("2014-01-27")); // Mon Jan 27 2014 08:00:00 GMT+0800