Javascript vs Date - javascript

I have some interesting problem and can't find the solution. Look at this:
var d1 = new Date("07 31 2014");
document.write(d1);
document.write('<br />');
var d2 = new Date(1406746800 * 1000);
document.write(d2);
when I run this script I get this result:
Thu Jul 31 2014 00:00:00 GMT+0500 (UZT)
Thu Jul 31 2014 00:00:00 GMT+0500 (UZT)
then after I changed my time zone I get this result:
Thu Jul 31 2014 00:00:00 GMT-0800 (AKDT)
Wed Jul 30 2014 11:00:00 GMT-0800 (AKDT)
as you can see the second result is Jul 30, but first result is Jul 31. I think they must both be equal to 31 Jul. I know this problem depends on the timezone but is there a solution?

So the constructor parameter is:
an Integer value representing the number of milliseconds since 1
January 1970 00:00:00 UTC
So given your integer value, that represents (for me, in BST):
Wed Jul 30 2014 20:00:00 GMT+0100
Which is
Wed Jul 30 2014 19:00:00 UTC
And your timezone is GMT-8, so thats the above -8 which gives:
Wed Jul 30 2014 11:00:00 GMT-0800 AKDT
The date string constructor constructs the date in your local timezone. You can see what the value should be by doing this:
new Date("07 31 2014").getTime() / 1000
Which returns 1406761200, not 1406746800

Related

Transform date to wire format (YYYY-MM-DD) in javascript

Having this input: Wed Feb 03 2021 00:00:00 GMT+0200 (Eastern European Standard Time), is there a way to format it as YYYY-MM-DD, to it will become 2021-02-03?
Try this:
const date = moment(new Date('Wed Feb 03 2021 00:00:00 GMT+0200 (Eastern European Standard Time)')).format('YYYY-MM-DD');
console.log(date);
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.29.1/moment.min.js" integrity="sha512-qTXRIMyZIFb8iQcfjXWCO8+M5Tbc38Qi5WzdPOYZHIlZpzBHG3L3by84BBBOiRGiEb7KKtAOAs5qYdUiZiQNNQ==" crossorigin="anonymous"></script>
Parsing a timestamp to a date to reformat it may well produce incorrect results if the timestamp includes an offset or timezone. Given "Wed Feb 03 2021 00:00:00 GMT+0200 (Eastern European Standard Time)", for a user with an offset of +1 or less the date will be 2 Feb, not 3 Feb.
The most reliable method is to reformat the string, e.g.
let timestamp = "Wed Feb 03 2021 00:00:00 GMT+0200 (Eastern European Standard Time)";
let months = [,'Jan','Feb','Mar','Apr','May','Jun',
'Jul','Aug','Sep','Oct','Nov','Dec'];
let pad = n=>('0'+n).slice(-2);
let p = timestamp.split(' ');
console.log(`${p[3]}-${pad(months.indexOf(p[1]))}-${p[2]}`);

Create date from number of days

I am trying to convert the number of days since Jan 01 1970 to JavaScript Date.
Here is the code snippet.
new Date(864e5 * parseInt(data[i].d));
//here data[i].d contains number of days.
I checked all the data by this.
console.log(typeof(data[i].d), data[i].d);
//prints
number 17674
but sometimes it unable to convert it into date.
Invalid Date {}
while for
number 17858
//outputs.
Fri Aug 17 2018 05:00:00 GMT+0500 (Pakistan Standard Time)
Thanks for your time.
You just have to add the number of days times the milliseconds in a day, like so:
var originalDay = new Date(864e5)
console.log(originalDay) //Thu Jan 01 1970 19:00:00 GMT-0500 (Eastern Standard Time)
var numOfDays = 7
var daysSince = new Date(864e5 + parseInt(numOfDays * 864e5))
console.log(daysSince) //Thu Jan 08 1970 19:00:00 GMT-0500 (Eastern Standard Time) --7 days later
To make this work for you, you would just have to replace that numOfDays with the values in your array.

Why are those dates different?

Here the console output:
new Date(2016, 08, 22)
Thu Sep 22 2016 00:00:00 GMT+0200 (CEST)
new Date("2016, 08, 22")
Mon Aug 22 2016 00:00:00 GMT+0200 (CEST)
Different months but why ?
Javascript months are 0 based in the numeric case, but in the string parsing 08 is mapped to August as it is a string translation of "August" in standard date format.
Date is being invoked in different ways as mentioned here
new Date();
new Date(value);
new Date(dateString);
new Date(year,month[, day[, hour[, minutes[, seconds[, milliseconds]]]]]);
In your case, 3 & 4 formats are being called.
>> new Date(2016, 08, 22)
>> Thu Sep 22 2016 00:00:00 GMT+0530 (IST)
>> new Date(2016, 01, 22)
>> Mon Feb 22 2016 00:00:00 GMT+0530 (IST)
>> new Date(2016, 0, 22)
>> Fri Jan 22 2016 00:00:00 GMT+0530 (IST)
>> new Date("2016-08-22")
>> Mon Aug 22 2016 05:30:00 GMT+0530 (IST)
>> new Date("2016/08/22")
>> Mon Aug 22 2016 00:00:00 GMT+0530 (IST)
#RobG's input from the comments:
...parsing ofstrings other than ISO 8601 extended format is entirely
implementation dependent. The result of parsing "2016, 08, 22" could be anything, including an invalid Date.
The second Date constructor you use is intended to parse a (known) string representation of a date, like "Dec 25, 1995". The format you pass in is not a standard one, so even though the result is close to the correct date (and could be fixed by correcting the month value, as pointed out by DhruvPathak), it should not be used as results my differ depending on the runtime/browser.

How to compare dates to see where adjacent times meet?

I have dates currently formatted in the following way:
[ [ Tue Jun 17 2014 09:00:00 GMT-0400 (EDT),
Tue Jun 17 2014 10:00:00 GMT-0400 (EDT) ] ]
[ [ Thu Jun 19 2014 09:30:00 GMT-0400 (EDT),
Thu Jun 19 2014 11:30:00 GMT-0400 (EDT) ] ]
[ [ Tue Jun 17 2014 10:00:00 GMT-0400 (EDT),
Tue Jun 17 2014 11:00:00 GMT-0400 (EDT) ] ]
These dates are actually "sessions", and I need to see where certain sessions are adjacent to each other. For example, in this specific case, the first array of dates has a end time of 10AM while the last array of dates has a start time for 10AM. How can I computationally find this situation?
The one approach I have is to first sort the array sets from earliest time to to latest time, and then compare each of the start/end date pairs to see if they are the same, but I can't seem to get it through. Any ideas are welcome!
Turn the strings into Unix timestamps with Date.parse() (if these are actually Date objects, then use the .getTime() method) and then order the sessions with Array.prototype.sort(). Here's an example where the sessions are ordered by start time:
var sessions = [
["Tue Jun 17 2014 09:00:00 GMT-0400 (EDT)", "Tue Jun 17 2014 10:00:00 GMT-0400 (EDT)"],
["Thu Jun 19 2014 09:30:00 GMT-0400 (EDT)", "Thu Jun 19 2014 11:30:00 GMT-0400 (EDT)"],
["Tue Jun 17 2014 10:00:00 GMT-0400 (EDT)", "Tue Jun 17 2014 11:00:00 GMT-0400 (EDT)"]
];
for (var i = 0; i < sessions.length; i++) {
sessions[i].startTime= Date.parse(sessions[i][0]);
}
sessions.sort(function(a, b) { return a.startTime-b.startTime; });

Strange Date( )'s created with Strings containing NULL bytes

I know that JavaScript doesn't NULL terminate strings like C or C++ do, but I ran into a case which I can't explain.
Look at the following code (executed in Node.js v0.10.5) :
> new Date('123')
Fri Jan 01 123 00:00:00 GMT+0100 (CET) // UNIX epoch : -58285702800000
> new Date('123\056')
Fri Jan 01 123 00:00:00 GMT+0100 (CET) // UNIX epoch : -58285702800000
> new Date('123\0456')
Tue Jun 01 123 00:00:00 GMT+0200 (CEST) // UNIX epoch : -58272660000000
> new Date('123\0567')
Thu Jul 01 123 00:00:00 GMT+0200 (CEST) // UNIX epoch : -58270068000000
> new Date('123\0999')
Fri Jan 01 123 00:00:00 GMT+0100 (CET) // UNIX epoch : -58285702800000
> new Date('123\0555')
Sat May 01 123 00:00:00 GMT+0200 (CEST) // UNIX epoch : -58275338400000
> new Date('123\0655')
Sat Jan 01 12355 00:00:00 GMT+0100 (CET) // UNIX epoch : 327718911600000
I'm not sure what's happening here, can someone explain it to me ?
It would seem that sometimes, the integers after a NULL byte define the month of the date, but the month not always correspond to the following number.
Those are 3-digit octal escapes, not null bytes. So for example '123\0456' is realy '123%6'.

Categories

Resources