How does javascript Date interpret the milisecond integers?
var d = new Date(-1724115600000); //this gives me a date in the past, which I want
console.log(d);
var d = new Date(1724115600000);
console.log(d);
(we had a bug where the - sign was not getting through. But I dont understand the significance of the -)
The Date object constructor can take a variety of inputs, but when called in this fashion it's using the integer value one:
Integer value representing the number of milliseconds since 1 January 1970 00:00:00 UTC (Unix Epoch).
Negative values will give dates before the Unix Epoch, positive values are dates after the Epoch.
0 would be 1. January 1970. The delta is given as an unsigned number representing milliseconds. If you want dates before that you need to use negative values in milliseconds.
The negative number you provided will give a number in the past, the other one in the future:
Date 1915-05-14T23:00:00.000Z
Date 2024-08-20T01:00:00.000Z
If you got one in the past with the second number it may have been missing the last digit when your tried. In that case it would give:
Date 1975-06-19T12:06:00.000Z
var d = new Date(-1724115600000); //this gives me a date in the past, which I want
document.write(d + "<br>");
var d = new Date(1724115600000); //This gives me a date in the past too.
document.write(d + "<br>");
var d = new Date(172411560000); //missing last digit
document.write(d);
//negative sign give you the date before 1970. in your example
var d = new Date(-1425223942000);// this gives date in the past
document.write(d) //Sun Nov 02 1924 03:27:38 GMT-0500 (Eastern Standard Time)
document.write('<br/>')
var d = new Date(1425223942000); //This gives date in th future.
document.write(d); // Sun Mar 01 2015 10:32:22 GMT-0500 (Eastern Standard Time)
//Unfortunately i cannot post the screenshots yet
Related
In JavaScript, I have two vars (aankomstDatum & vertrekDatum) containing a checkin date and a checkout date in the "dd-mm-yy" format. These vars come from text input fields with a jQuery datepicker.
I want to calculate the price of the stay according to aankomstDatum and vertrekDatum, so it's correct I still have to convert the vars to dates? I did it with the following code starting from dd-mm-yy:
var parts = aankomstDatum.split('-');
var aankomstDatumDate = new Date(parts[2],parts[0]-1,parts[1]);
document.getElementById("aankomstDate").innerHTML = aankomstDatumDate;
When I output aankomstDatumDate I get a working date in the following format: Sat Nov 11 2017 00:00:00 GMT+0100 (Romance Standard Time).
My two questions:
1) Is this step necessary? Is my train of thought correct that I start with dates and convert them to dates first before I can use them to calculate a booking price?
2) Is the outputted date Sat Nov 11 2017 00:00:00 GMT+0100 (Romance Standard Time) okay to use to calculate the booking price? Or is it way better to have it in a format like "dd-mm-yy"? And if so, how do I achieve that?
Answering your two questions:
Yes, this train of thought is correct -- you want to convert your strings into Date objects so that you can do operations on those dates.
If you are planning on using some sort of arithmetic on the dates, you probably want to use getTime() on those dates, which returns the dates in Unix Time (milliseconds).
For example, if you wanted to calculate the number of days that a user was checked in for (checkoutDate - checkinDate), you would use this function, which accepts two date objects:
function daysDifference(date1, date2) {
let diff = date2.getTime() - date1.getTime();
return Math.round(diff / (1000*60*60*24)); // divide by number of milliseconds in a day
}
// Example
var date1 = new Date(); // today
var date2 = new Date();
// add 5 days to date2
date2.setDate(date2.getDate() + 5);
var daysCheckedIn = daysDifference(date1, date2);
console.log("User checked in for: " + daysCheckedIn + " days.");
I'm using the Angular UI Bootstrap Datepicker and Timepicker (https://angular-ui.github.io/bootstrap/), and I want to combine both of those values and get the current millis. I get the date in this format: "2015-05-19" [YYYY-MM-DD"] and the time as this: "10:57:19" [HH:MM:SS].
I saw that there is a Date.parse() method where you can get current millis but I couldn't find a way where you can include a time as well, and was wondering if there was a method for this?
Since you already have a date and a time, you could use these to construct a date string:
var date = '1970-01-01';
var time = '00:00:00';
var dateString = date + 'T' + time; // '1970-01-01T00:00:00'
var parsedDate = Date.parse(dateString); // 0 Milliseconds
The 'T' is for handling timezones. Since I'm located in central Europe, my timezone offset is GMT+1 (Central European Time).
var newDate = new Date(parsedDate); // Thu Jan 01 1970 01:00:00 GMT+0100 (CET)
looks like the answer would be: Date.parse('MM DD YYYY HH:MM:SS');
from https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date/parse
but you probably need to be wary of the time zone.
I'm creating dates like this:
var StartDate = new Date(data.feed.entry[i].gd$when[j].startTime);
When a date string is received specifying date and time in the form:
"2014-04-12T20:00:00.000-05:00"
Date() interprets this perfectly fine returning:
Sat Apr 12 2014 19:00:00 GMT-0500 (CDT)
However, when the date string is received with no time information in the form:
"2014-04-07"
then Date() is interpreting it as:
Sat Apr 05 2014 19:00:00 GMT-0500 (CDT)
Looks like Date() is taking the -07 as the time and I have no clue where is it getting the date as 05. Any idea what might be the problem?
Could it be, somehow, Date() is interpreting a different time zone because in the first string the time zone is determined at the very end but in the "all day" event there is no indication of the time zone.
Has anybody found this issue? If yes, how did you solve it?
UPDATE: After researching a little bit more this parsing issue I noticed something very weird:
The following statement:
new Date("2014-4-07")
would return Mon Apr 07 2014 00:00:00 GMT-0500 (CDT) which is correct, but the following one:
new Date("2014-04-07")
returns Sun Apr 06 2014 19:00:00 GMT-0500 (CDT) which is the wrong one. So, for whatever reason, seems like the padding zeros affect the way the date is parsed!
You're using the Date() function wrong.
It only accepts parameters in the following formats.
//No parameters
var today = new Date();
//Date and time, no time-zone
var birthday = new Date("December 17, 1995 03:24:00");
//Date and time, no time-zone
var birthday = new Date("1995-12-17T03:24:00");
//Only date as integer values
var birthday = new Date(1995,11,17);
//Date and time as integer values, no time-zone
var birthday = new Date(1995,11,17,3,24,0);
Source: MDN.
The Date() function does not accept timezone as a parameter. The reason why you think the time-zone parameter works is because its showing the same time-zone that you entered, but that's because you're in the same time-zone.
The reason why you get Sat Apr 05 2014 19:00:00 GMT-0500 (CDT) as your output for Date("2014-04-07" ) is simply because you used it in a different way.
new Date(parameters) will give the output according to the parameters passed in it.
Date(parameters) will give the output as the current date and time no matter what parameter you pass in it.
Prior to ES5, parsing of date strings was entirely implementation dependent. ES5 specifies a version of ISO 8601 that is supported by may browsers, but not all. The specified format only supports the Z timezone (UTC) and assumes UTC if the timezone is missing. Support where the timezone is missing is inconsistent, some implementations will treat the string as UTC and some as local.
To be certain, you should parse the string yourself, e.g.
/* Parse an ISO string with or without an offset
** e.g. '2014-04-02T20:00:00-0600'
** '2014-04-02T20:00:00Z'
**
** Allows decimal seconds if supplied
** e.g. '2014-04-02T20:00:00.123-0600'
**
** If no offset is supplied (or it's Z), treat as UTC (per ECMA-262)
**
** If date only, e.g. '2014-04-02', treat as UTC date (per ECMA-262)
*/
function parseISOString(s) {
var t = s.split(/\D+/g);
var hasOffset = /\d{2}[-+]\d{4}$/.test(s);
// Whether decimal seconds are present changes the offset field and ms value
var hasDecimalSeconds = /T\d{2}:\d{2}:\d{2}\.\d+/i.test(s);
var offset = hasDecimalSeconds? t[7] : t[6];
var ms = hasDecimalSeconds? t[6] : 0;
var offMin, offSign, min;
// If there's an offset, apply it to minutes to get a UTC time value
if (hasOffset) {
offMin = 60 * offset / 100 + offset % 100;
offSign = /-\d{4}$/.test(s)? -1 : 1;
}
min = hasOffset? +t[4] - offMin * offSign : (t[4] || 0);
// Return a date object based on UTC values
return new Date(Date.UTC(t[0], --t[1], t[2], t[3]||0, min, t[5]||0, ms));
}
An ISO 8601 date string should be treated as UTC (per ECMA-262), so if you are UTC-0500, then:
new Date('2014-04-07'); // 2014-04-06T19:00:00-0500
The behaviour described in the OP shows the host is not compliant with ECMA-262. Further encouragement to parse the string yourself. If you want the date to be treated as local, then:
// Expect string in ISO 8601 format
// Offset is ignored, Date is created as local time
function parseLocalISODate(s) {
s = s.split(/\D+/g);
return new Date(s[0], --s[1], s[2],0,0,0,0);
}
In your function you can do something like:
var ds = data.feed.entry[i].gd$when[j].startTime;
var startDate = ds.length == 10? parseLocalISODate(ds) : parseISOString(ds);
Also note that variables starting with a capital letter are, by convention, reserved for constructors, hence startDate, not StartDate.
(I would add a comment but i don't have 50 rep yet)
See what
new Date().getTimezoneOffset()
returns, I would expect a big negative value, that would be the only reasonable explanation to your problem.
I have had some trouble with date conversions in the past, in particular with daytime saving timezones, and as work around i always set the time explicitly to midday (12:00am). Since I think you were using knockout, you could just make a computed observable that appends a "T20:00:00.000-05:00" or the appropiate time zone to all "day only" dates
I'm developing with node.js, and I'm trying to create a date object on the server.
when coding:
var birthyear = 2000;
var birthmonth = 7;
var birthday = 24;
var date = new Date(birthyear, birthmonth, birthday);
console.log(date);
OUTPUT:
Thu Aug 24 2000 00:00:00 GMT+0300 (Jerusalem Daylight Time)
As you can see, I'm getting August instead of July.
How can I fix that issue ?
The month argument in the Date() constructor doesn't start at 1 for January, but instead at 0. Therefore, supplying the month value of 7 gives you the eight month, which is August.
From MDN:
month: Integer value representing the month, beginning with 0 for January to 11 for December.
Months in JS start at 0
so it's a quite an easy fix:
var date = new Date(birthyear, birthmonth-1, birthday);
DEMO
Months in the JavaScript Date() constructor are 0-indexed, meaning that month 7 actually is August. Use the value 6 for July.
Annoyingly enough, Date is rather inconsistent about which fields are 0-indexed and which are 1-indexed, and in fact the same field can be either one depending on the context. You should always refer to documentation when you have to use dates.
Yea, that's weird, but months should be counted starting with
0
I'm splitting an array, when I take the middle of the array which is reporting as epoch date in milliseconds. I'm testing the date using Epoch Converter and its valid.
I run the date() object and multiply by 1000 to adjust but I'm getting year 4000. I've switched to division just to test if I'm getting too large of a number the year is correct but the day and months are wrong....I've got to be missing something simple:
var jEtrim = item.DTM.split(/[(-]/);
var date = new Date(jEtrim[1] *1000);
sample output: Thu Jan 08 44037 07:03:20 GMT-0500 (Eastern Standard Time)
Here's the jEtrim: ["/Date", "1343151455000", "0400)/"]
Thanks in advance
Date takes its argument in milliseconds already, so you will not need to multiply by 1000. You will only need to convert it to a number:
new Date(+"1343151455000")