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
Related
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 have div in which I am providing date and time like this
<div class="timing">
<div id="count-down" data-date="2016-08-31 14:21:00"> </div>
</div>
How would I match or compare with current date, because I am getting current date in this format Wed Aug 31 2016 14:34:58 GMT+0500 (Pakistan Standard Time)
I want to redirect a page to new location if current date is greater than provided date
var currentDate = new Date();
var providedDate = $('#count-down').attr('data-date')
if (currentDate.getDate().toString > providedDate)
{
window.location.href = 'Promo';
$('.timing').css("display", "none");
$('.website-loading').css("display", "block");
}
I have div in which I am providing date and time like this
<div id="count-down" data-date="2016-08-31 14:21:00"> </div>
The string in the data- attribute is not consistent with the format specified in ECMA-262 (the "T" separator between the date and time is missing), so you should manually parse it by either writing a parsing function or use a library and provide the format to parse.
If you use the Date constructor (or Date.parse, they are equivalent for parsing) to parse the string, you may get an invalid date (e.g. in Safari, new Date('2016-01-01 12:00:00') produces an invalid date) since parsing of non–standard strings is entirely implementation dependent.
There are many suitable libraries, some suggestions:
moment.js does parsing, formatting, timezones and arithmetic and has a CDN
fecha.js just does parsing and formatting is very much smaller than moment.js
When you create a Date object, it only has one internal value (called its time value), which is milliseconds since 1970-01-01T00:00:00Z (the javascript epoch, which is the same as the UNIX epoch). When you call the toString method, the result is an implementation dependent string that differs between implementations (in your case you see something like "Wed Aug 31 2016 14:34:58 GMT+0500 (Pakistan Standard Time)", a different implementation may produce something else.
How would I match or compare with current date, because I am getting
current date in this format Wed Aug 31 2016 14:34:58 GMT+0500 (Pakistan Standard Time)
When comparing dates, you really just want to compare the time value. If you compare using the relational operators > or <, they will coerce the dates to their time value so you can compare the dates directly, e.g.:
var providedDate = fecha.parse($('#count-down').attr('data-date'), 'YYYY-MM-DD HH:mm:ss');
if (Date.now() > providedDate) {
// providedDate is in the past
}
Note that since no time zone information is provided in the string to parse, it's treated as a "local" date and time and the host system's current settings are used to determine the offset from UTC, which is then used when calculating the time value. The same system works in reverse when generating a local date and time string from the Date using the default toString method.
Also:
currentDate.getDate()
just returns the date (i.e. the day in the month) as a number without the year and month.
I am based in Australia and while new Date() give me the current date and time in Australia, for instance
Fri Aug 26 2016 09:16:16 GMT+1000 (AUS Eastern Standard Time)
, if I write new Date().toJSON()
I get 2016-08-25T23:20:08.242Z,
how can I get the same format as in yyyy-mm-ddThh:mn:ss but keeping my local day and time, ie it should be the 26 and not the 25th.
Edit: when I write programmatically new Date(2016, 11, x) with var x = 31, using toJSON() I have no guarantee to see displayed 2016-12-31 because of timezones, so was wondering is there is a different javascript function that would give me the intended result.
I would use moment.js for that.
var date = moment("Fri Aug 26 2016 09:16:16 GMT+1000");
console.log(moment(date).format('YYYY-MM-DD T hh:mm:ss'));
https://jsfiddle.net/Refatrafi/ys4nu8o9/
toJSON() returns timestamps in ISO 8601 format. Z at the end of string means that used UTC. Date objects in ECMAScript are internally UTC. The specification for Date.prototype.toJSON says that it uses Date.prototype.toISOString, which states that "the timezone is always UTC".
The date isn't wrong, it's in UTC. Without timezone information, yyyy-mm-ddThh:mn:ss is meaningless unless you explicitly want to assume that it's in the AEST timezone.
If you're transmitting the date as a string to be parsed back into some sort of Date-like object later on (by your webserver, for example), there's nothing you need to do. 2016-08-25T23:20:08.242Z unambiguously refers to the same point in time no matter what you use to parse it.
If you're trying to format the date object and display it somewhere, you can extract the different parts of the Date object and build up the representation you want:
function format_date(d) {
var pretty_date = [d.getFullYear(), d.getMonth() + 1, d.getDate()].join('-');
var pretty_time = [d.getHours(), d.getMinutes(), d.getSeconds()].join(':');
return pretty_date + 'T' + pretty_time;
}
As the other answers have pointed out, if you plan on working more with dates, consider using a library that makes it easier. JavaScript doesn't have a very rich API, so you'll have to write more code.
I'm trying to convert a date string into a date object without changing the timezone. Here is the standard behavior:
new Date ("2014-10-24T00:00:00")
result
Thu Oct 23 2014 19:00:00 GMT-0500 (Central Daylight Time)
I am able to reverse the timezone by getting the offset in minutes, multiplying it by 60,000, and then adding that to the new string date.
new Date(new Date("2014-10-24T00:00:00").getTime() + new Date().getTimezoneOffset()*60000)
This works, but it seems like there must be a better way that doesn't require created three date objects.
Do not parse strings using the Date constructor. It calls Date.parse which, despite being standardised for one version of ISO 8601 strings in ES5, is still almost entirely implementation dependent.
I'm trying to convert a date string into a date object without changing the timezone.
> new Date ("2014-10-24T00:00:00")
That string will be treated differently in different browsers. If you want it to be treated as UTC, then it is simple to parse yourself:
function parseISOAsUTC(s) {
var b = s.split(/\D/);
return new Date(Date.UTC(b[0],--b[1],b[2],b[3],b[4],b[5],(b[6]||0)));
}
console.log(parseISOAsUTC('2014-10-24T00:00:00').toISOString()); // 2014-10-24T00:00:00.000Z
Now you can be certain that the string will be treated as UTC in all browsers in use (including the 20% or so still using IE 8 and lower).
If, on the other hand, you want the string to be treated as a local time, then just remove the Date.UTC part:
function parseISOAsLocal(s) {
var b = s.split(/\D/);
return new Date(b[0],--b[1],b[2],b[3],b[4],b[5],(b[6]||0));
}
console.log(parseISOAsLocal('2014-10-24T00:00:00')); // Fri 24 Oct 2014 00:00:00 <local timezone>
Here is an implementation of zerkms's solution.
new Date("2014-10-24T00:00:00".replace('T', ' '))
result
Fri Oct 24 2014 00:00:00 GMT-0500 (Central Daylight Time)
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()