This question already has answers here:
How to calculate number of days between two dates?
(42 answers)
Closed 3 years ago.
Consider I have an array of dates eg:
abc = [new Date("2015-03-01"),new Date("2015-03-02"),new Date("2015-03-03"),new Date("2015-03-04")]
output:
[Sun Mar 01 2015 05:30:00 GMT+0530 (India Standard Time), Mon Mar 02 2015 05:30:00 GMT+0530 (India Standard Time), Tue Mar 03 2015 05:30:00 GMT+0530 (India Standard Time), Wed Mar 04 2015 05:30:00 GMT+0530 (India Standard Time)]
I'm trying to push the difference between two dates and trying to store the data in a new array.
Here is what I have tried,
var arr = [];
abc = [new Date("2015-03-01"),new Date("2015-03-01"),new Date("2015-03-02"),new Date("2015-03-03"),new Date("2015-03-04")];
for (let i = 0; i < abc.length-1; i++){
arr.push((abc[i+1].getDate() - abc[i].getDate())+1)
}
And the output I'm getting is:
[1,2, 2, 2]
But I needed the output something like
[1,2,3,4]
I need to append plus one to each date difference. How can I achieve that?
Dates in the format YYYY-MM-DD are parsed as UTC, where every day (in ECMAScript) is exactly 8.64e7 ms long making simple arithmetic, well, simple. :-)
Since the dates are whole days and treated as UTC, you can just subtract the dates from each other and divide by 8.64e7 to get whole days difference.
Also, you seem to want the difference from the first date, so hold that constant, e.g.
let arr = [];
let abc = [new Date("2015-03-01"),new Date("2015-03-01"),new Date("2015-03-02"),new Date("2015-03-03"),new Date("2015-03-04")];
for (let i = 0; i < abc.length-1; i++){
arr.push(1 + (abc[i+1] - abc[0])/8.64e7);
}
console.log(arr);
Is this what you want?
abc = [new Date("2015-03-01"),new Date("2015-03-01"),new Date("2015-03-02"),new Date("2015-03-03"),new Date("2015-03-04")];
const result = abc.slice(1).map(date => ~~((date-abc[0]) / (24*60*60*1000)) + 1)
console.log(result)
Related
i have this code which works with dates:
let startDate = new Date(toolOrder.jsAppStartDate.getTime()); // clone date
startDate.setDate(startDate.getDate() - Math.floor((days - 1) / 2)); // sub some days
console.log(toolOrder.jsAppStartDate); // Output: Date Thu Sep 21 2023 00:00:00 GMT+0200 (Central European Summer Time)
console.log(toolOrder.jsAppStartDate.getTime()); // Output: 1695247200000
console.log("--------------");
for (let index = 0; index < days; index++)
{
console.log(startDate);
console.log(startDate.getTime());
// ... some drawing code here ...
startDate.setDate(startDate.getDate() + 1); // add one day
if(startDate === toolOrder.jsAppStartDate) // check if start date reached
{
console.log("Dates match");
startDate = new Date(toolOrder.jsAppEndDate.getTime());
}
}
The output of the log before the loop is:
Date Thu Sep 21 2023 00:00:00 GMT+0200 (Central European Summer Time)
1695247200000
---------------
The output from the loop is:
Date Mon Sep 18 2023 00:00:00 GMT+0200 (Central European Summer Time)
1694988000000
Date Tue Sep 19 2023 00:00:00 GMT+0200 (Central European Summer Time)
1695074400000
Date Wed Sep 20 2023 00:00:00 GMT+0200 (Central European Summer Time)
1695160800000
Date Thu Sep 21 2023 00:00:00 GMT+0200 (Central European Summer Time)
1695247200000
Date Fri Sep 22 2023 00:00:00 GMT+0200 (Central European Summer Time)
1695333600000
So even if the dates match in loop 3, the if condition is not true. It works when I use
if(startDate.getTime() === toolOrder.jsAppStartDate.getTime())
but I thought it should work without also?
=== compares identity so:
startDate === toolOrder.jsAppStartDate
Means: is startDate the same object [in memory] as toolOrder.jsAppStartDate which is not the case because toolOrder.jsAppStartDate is a different object and not the object referred to by the name startDate.
mdn says this about the strict equality operator:
If both operands are objects, return true only if they refer to the same object.
(emphasis mine)
if(startDate.getTime() === toolOrder.jsAppStartDate.getTime())
Works because you're now comparing numbers instead of objects.
The rule for the two operands being numbers is:
Otherwise, compare the two operand's values:
Numbers must have the same numeric values. +0 and -0 are considered to be the same value.
mdn (emphasis mine)
You are comparing Date instances with each other when you're using the === operator. However, they are not the same instance. Each new Date creates a unique, new instance (unless the class constructor deliberately returns a previously created instance [for more info: singleton pattern]).
When you are comparing each instance's getTime() result, you are comparing 2 primitive values (numbers in this case). Primitive values are not class instances; so === works like == with primitives.
I get a date string as Fri Sep 17 2021 11:50:59 GMT-0400 (Eastern Daylight Time) from one place. I get it from 2021-09-17T11:50:59-04:00 in a second place.
I want to convert the first format to the second.
I am doing this in a crazy way, so I am thinking there must be a better one.
var d = new Date(`Fri Sep 17 2021 11:50:59 GMT-0400 (Eastern Daylight Time)`);
var iso = d.toISOString();
var time = d.toTimeString();
console.log(iso);
console.log(time);
var [date] = iso.split('T')
var [,localTime, timezone] = time.match(/([^ ]+) GMT([^ ]+)/);
var timezoneWithColon = timezone.replace(/(-*[0-9]{2,2})([0-9]{2,2})/,"$1:$2")
var desiredFormat = '2021-09-17T11:50:59-04:00';
var convertedFormat = `${date}T${localTime}${timezoneWithColon}`;
console.log(desiredFormat)
console.log(convertedFormat)
console.log(desiredFormat === convertedFormat);
The fiddle is over at https://jsfiddle.net/Dave_Stein/8tLv2g4j/.
2021-09-17T11:50:59-04:00 is an ISO-8601 date string.
toISOString should work, however it will convert the time to UTC. If you want this to format in your current timezone, you'll have to use a library such as date-fns:
import { formatISO } from 'date-fns'
formatISO(new Date(`Fri Sep 17 2021 11:50:59 GMT-0400 (Eastern Daylight Time)`))
// prints '2021-09-17T11:50:59-04:00'
I'm reading data from a API server:
opTMP:
{ DATAI: "2019-10-27T00:00:00", …}
{ DATAI: "2019-10-31T00:00:00", …}
then I create a new date:
const opTMP1 = this.opTMP.map(x => Object.assign({}, x));
for (const op of opTMP1){
let d = new Date(op.DATAI);
console.log(d);
...
}
but in console I got different results,one is GMT+0300 and one GMT+0200 :
d: Sun Oct 27 2019 00:00:00 GMT+0300 (Eastern European Summer Time)
d: Thu Oct 31 2019 00:00:00 GMT+0200 (Eastern European Standard Time)
because of that I got problems when comparing it,I want to get only day month and year,no time info needed,how can I reset both to the same time or to 0:00:00?
Converting date to epoch time is good way to comparing the dates.
let d = new Date(op.DATAI).getTime();
I have a start date and an end date, and I want to generate a list of dates between (and including) these two dates. But I don't get why it isn't working...
I pass in a couple of JS date objects, I've shown what they log to the console below
function dateList(dateStart, dateEnd) {
console.log(dateStart);
console.log(dateEnd);
var dates = [];
for ( i = dateStart; i <= dateEnd; i.setDate(i.getDate() + 1) ){
dates.push(i);
}
return dates
}
Mon May 08 2017 00:00:00 GMT+0100 (BST)
Fri May 12 2017 00:00:00 GMT+0100 (BST)
The array that is returned is
Array[5]
0: Sat May 13 2017 00:00:00 GMT+0100 (BST)
1: Sat May 13 2017 00:00:00 GMT+0100 (BST)
2: Sat May 13 2017 00:00:00 GMT+0100 (BST)
3: Sat May 13 2017 00:00:00 GMT+0100 (BST)
4: Sat May 13 2017 00:00:00 GMT+0100 (BST)
length: 5
__proto__: Array[0]
...Why???......
Try to add new Date(i), instead of just i:
function dateList(dateStart, dateEnd) {
var dates = [];
for (i = dateStart; i <= dateEnd; i.setDate(i.getDate() + 1)){
dates.push(new Date(i));
}
return dates;
}
console.log(dateList(new Date('2017-05-08'), new Date('2017-05-12')));
Your code i.setDate(i.getDate() + 1) doesn't create a new date - it just updates the same Date object over and over. Then you push that object onto the array, which pushes a reference to that object - not a copy of the object.
A solution would be to create a new Date() inside the loop and setting the value of it, and then pushing this new date onto your array.
Because the same object is modified all elements referencing the same object
Can somebody please help me construct a regular expression in Javascript to check if year 2017 exists or a year starting with 19 or 20 (century) exists in a given date.
My date format is : Fri Dec 01 2017 00:00:00 GMT-0800 (Pacific Standard Time).
I tried this but it fails:
var str = "Fri Dec 01 2017 00:00:00 GMT-0800 (Pacific Standard Time)";
var patt = new RegExp("/^\S{3}[\s]\S{3}[\s]\d{2}[\s]\d{4}$/");
var res = patt.test(str);
Thanks,
Haseena
You can use Date.getFullYear() method.
var d = new Date("Fri Dec 01 1999 00:00:00 GMT-0800 (Pacific Standard Time)");
var year = d.getFullYear();
Here is example you can use.
var str="Fri Dec 01 2017 00:00:00 GMT-0800 (Pacific Standard Time)";
var patt=/(\w{3}\s){2}\d{2}\s(\d{4})\s(.*)/;
var results = patt.exec(str);
console.log(results);
console.log(results[2]);
The second group is match the year.
The year validation with multiple condition is not quite a regex thingy
If I have understood your question then you can try this:
^[a-zA-Z]{3}\s+[A-Za-z]{3}\s+\d{2}\s+(2017|(?:19\d{2}|20\d{2}))\s+.*
It will only match if the year is 2017
It will match if the year starts with 19
It will match if the year starts with 20
If match is found, then the year can be found in group 1
Explanation
const regex = /^[a-zA-Z]{3}\s+[A-Za-z]{3}\s+\d{2}\s+(2017|(?:19\d{2}|20\d{2}))\s+.*$/gm;
const str = `Fri Dec 01 2017 00:00:00 GMT-0800 (Pacific Standard Time)`;
let m;
if((m = regex.exec(str)) !== null) {
console.log("Full match ="+m[0]);
console.log("Matched year ="+m[1]);
}
else
console.log("no match found");
With a fixed date format, this is really easy:
First, just extract your year using a regular expression var year = str.match(/^.{11}(\d{4})/)[1]
.match returns an array where the first element is the entire matched string and subsequent elements are the parts captured in parentheses.
After you have this, you can test if year === '2017' or if year.substr(0, 2) === '19'.
There are about a dozen other ways to do this, too.
var myDate = 'Fri Dec 01 2017 00:00:00 GMT-0800 (Pacific Standard Time)';
function isCorrectYear(dateString) {
var year = dateString.match(/^.{11}(\d{4})/)[1];
if (year === '2017') return true;
}
if (isCorrectYear(myDate)) {
alert("It's the correct year.");
}
Something just occurred to me... "year 2017 exists or a year starting with 19 or 20". Doesn't that cover every year in every date string you are ever likely to encounter? I don't think they had Javascript before the 1900s and I doubt anything any of us will write will still be in use after the year 2100.