Fill an array with dates - javascript

Really can't see why the dates I'm pushing into an array are not the dates that come out when I call the array in the console. i.e. I would expect the first entry in the array to be today's date, which is what comes back from both alert calls, but when I check the array's first position it has yesterday's date instead!?
function sevenDayPeriod(date) {
for (var i = 0; i <=6; i++) {
alert(date); //check to see date is today's date
dateRange[i] = date;
alert(dateRange[i]); //confirm that what I've pushed to array is today's date
date = date.setDate(date.getDate() - 1);
date = new Date(date);
}
};
var dateRange = [];
var today = new Date();
sevenDayPeriod(today);
Thanks

...
dateRange[i] = date;
alert(dateRange[i]); //confirm that what I've pushed to array is today's date
date = date.setDate(date.getDate() - 1);
...
In the first of the above lines you set the ith array element to date (a reference), then you show it and afterwards you change the same object with setDate which results in your problem, as the array element still points to that modified object.
You can solve that e.g. with another var like so
...
var prevDay = new Date();
prevDay.setDate(date.getDate() - 1);
date = prevDay;
...
or create a copy of it prior to pushing it into the array

function sevenDayPeriod(date) {
for (var i = 0; i <=6; i++) {
//date object is as a "pointer", you have to clone it
var copiedDate = new Date(date);
//alert(date); //check to see date is today's date
dateRange[i] = copiedDate;
//alert(dateRange[i]); //confirm that what I've pushed to array is today's date
date = date.setDate(date.getDate() - 1);
date = new Date(date);
}
};
var dateRange = [];
var today = new Date();
sevenDayPeriod(today);
console.log(dateRange);
When you modify the date, you are you're also changing pushed date. You have to clone it.

Related

How to find number of days from given days in js?

I need to find number of days if i enter startDate and endDate.from the start_date to end_date i only want to retrieve weekdays i.e monday to friday along with the offcial_leave variable
for_example:
let numberOfdays;
let startDate = '2022-04-04'; //yy-mm-dd format
let endDate = '2022-04-08';
// Below variable come from db and vary according the start and endate
// eg:- 2022-12-25 will be holiday if we select start and end in december
let holidays = ['2022-04-05', '2022-04-07' ]
numberOfdays => 3
// I want to return number of days to 3
How can i achieve this in in JavaScript
thanks
First convert the startDate and endDate to javascript Date. Then, declare a variable i to store while looping through the date. Also, declare holidayIndex which stores the current index at which holiday date needs to be checked with the current date.
Inside the loop, convert the date to YYYY-MM-DD format (original format) to check if the current date (isoDate) lies between a holiday, i.e., it is not a holiday date. If the holidayIndex is at last index of array, then just check if the current date (isoDate) is not in the holidays array. If not found, then increment numberOfDays variable.
Otherwise, a holiday date is found, hence no need to increment numberOfDays. Just increment holidayIndex to be ready to match the upcoming dates for next holiday date.
Here is the solution:
let numberOfdays = 0;
const startDate = '2022-04-04'; //yy-mm-dd format
const endDate = '2022-04-08';
// Below variable come from db and vary according the start and endate
// eg:- 2022-12-25 will be holiday if we select start and end in december
const holidays = ['2022-04-05', '2022-04-07'];
let holidayIndex = 0;
const start = new Date(startDate);
const end = new Date(endDate);
let i = start;
while (i <= end) {
const isoDate = i.toISOString().split('T')[0];
if (
(holidayIndex < holidays.length - 1 && isoDate < holidays[holidayIndex] && isoDate > holidays[holidayIndex + 1]) ||
formattedDate !== holidays[holidayIndex]
) {
numberOfdays += 1;
} else {
holidayIndex += 1;
}
i.setDate(i.getDate() + 1);
}

Add recurring date and time within range(StartDate and EndDate) using momentjs or javascript

I need an array of recurring dates with time for every week within the start date and end date using moment.js or javascript.
For example:
Startdate: 2021-10-04T00:00:00Z
Enddate: 2021-10-31T00:00:00Z
let's say 2021-10-05T00:00:00Z is a recurring date then output will be
["2021-10-05T00:00:00Z", "2021-10-12T00:00:00Z", "2021-10-19T00:00:00Z", "2021-10-26T00:00:00Z"]
We can use Date.getUTCDate() and Date.setUTCDate() to advance a date by a number of days, in this case seven.
We can then use a while loop to populate the result array. I'm returning an array of Date objects here, one could use .toISOString() to convert to strings.
let startDate = '2021-10-05T00:00:00Z';
let endDate = '2021-10-31T00:00:00Z';
function getWeeklyDates(start, end) {
let date = new Date(start);
const endDate = new Date(end);
const result = [];
while (date < endDate) {
result.push(date);
date = new Date(date);
date.setUTCDate(date.getUTCDate() + 7);
}
return result;
}
console.log(getWeeklyDates(startDate, endDate).map(dt => dt.toISOString()))
.as-console-wrapper { max-height: 100% !important; top: 0; }
You can do this with pure js if you remove the "Z" add "+00:00" to all of your strings to make sure your timezone does not break this code.
let start = "2021-10-04T00:00:00+00:00";
let end = "2021-10-31T00:00:00+00:00";
let date = "2021-10-05T00:00:00+00:00";
start = new Date(start);
end = new Date(end);
date = new Date(date);
let dates = [];
if (date < start) {
console.log("bad input")
} else {
while (date.getTime() < end.getTime()) {
dates.push(date.toISOString());
date = new Date(date.getTime() + 604800000); // add a week in milliseconds
}
}
you can do something like:
start at the first recurring date
add a week to the recurring date using .add(1, 'weeks') (see https://momentjs.com/docs/#/manipulating/add/ )
do this while recurring date < end date

Comparing Dates in NodeJS IF Statement

I am using nodejs/javascript and trying to compare two dates to each other in order to apply a specific style if the date is before the set date.
Here is what I have:
var d = new Date();
var date = d.getMonth()+1+'/'+d.getDate()+'/'+(d.getFullYear().toString().substr(-2)-1);
var da = new Date('1/4/18');
var da_test = da.getMonth()+1+'/'+da.getDate()+'/'+(da.getFullYear().toString().substr(-2));
if(da_test < date) {
// do something
}
date_test is currently returning the date from a year ago today, 1/23/18. I have set the other date that it will compare itself to, to 1/4/18. While this should be true, for some reason it is not whenever the IF statement runs. However, if I change the date to something like 1/2/18, then it returns true. How is that the case and how can it be changed so it will return true if it is any date before 1/23/18?
You can compare those two dates like this:
const d1 = new Date('1/23/18');
const d2 = new Date('1/4/18');
if (d2 < d1) ...
In your code example you are comparing two Strings
You can compare the milliseconds since epoch (the number of milliseconds since 1 January 1970 00:00:00)
const d1 = new Date('1/23/18');
const d2 = new Date('1/4/18');
if (d2.getTime() < d1.getTime()) {
}
You can also compare ISO date strings
const d1 = new Date('1/23/18');
const d2 = new Date('1/4/18');
if (d2.toISOString() < d1.toISOString()) {
}

Get days using two dates in js

I'm having this trouble where I can only get the days between specified 2 dates. Please see the code below:
var getDaysArray = function(start, end) {
for (var arr = [], dt = start; dt <= end; dt.setDate(dt.getDate() + 1)) {
arr.push(new Date(dt));
}
return arr;
};
var daylist = getDaysArray(new Date('08/13/2018'), new Date('08/17/2018'));
daylist.map((v) => v.toISOString().slice(0, 10)).join("");
console.log(daylist);
The output of the code above is:
Expected output (due to start and end dates 08/13/2018 and 08/17/2018):
0: Date 2018-08-13T16:00:00.000Z
1: Date 2018-08-14T16:00:00.000Z
2: Date 2018-08-15T16:00:00.000Z
3: Date 2018-08-16T16:00:00.000Z
4: Date 2018-08-17T16:00:00.000Z
Note: The code above was from one of the SO answers found somewhere.
toISOString represents the date in UTC format. You are probably in positive timezone offset, that's why the UTC representation of your date objects are a day off. You can use toLocaleString instead to represent your dates in your timezone.
Another issue is that Array.prototype.map retuns a new array, which you forgot to assign to daylist Without that assignment, no changes in daylist will be made.
Below snippet works as per your requirements.
var getDaysArray = function(start, end) {
for (var arr = [], dt = start; dt <= end; dt.setDate(dt.getDate() + 1)) {
arr.push(new Date(dt));
}
return arr;
};
var daylist = getDaysArray(new Date('08/13/2018'), new Date('08/17/2018'));
daylist = daylist.map((v) => v.toLocaleString());
console.log(daylist);

calculate difference between two timestamp and get difference in unix timestamp

I want to calculate the difference between two dateTime, one date is submitted by user and other is current time:
user submitted time - now = difference in unix
user submitted time format is:
2014-03-26 10:52:00
Thanks for your help.
You can simply do this with getTime() which returns the number of milliseconds.
var ds = "2014-03-26 10:52:00";
var newDate = new Date(ds).getTime(); //convert string date to Date object
var currentDate = new Date().getTime();
var diff = currentDate-newDate;
console.log(diff);
Sometimes there are chance for cross browser compatibility in parsing the date string so it is better to parse it like
var ds = "2014-03-26 10:52:00";
var dateArray = ds.split(" "); // split the date and time
var ds1 = dateArray[0].split("-"); // split each parts in date
var ds2 = dateArray[1].split(":"); // split each parts in time
var newDate = new Date(ds1[0], (+ds1[1] - 1), ds1[2], ds2[0], ds2[1], ds2[2]).getTime(); //parse it
var currentDate = new Date().getTime();
var diff = currentDate - newDate;
console.log(diff); //timestamp difference
You can use MomentJS library
var user_submited_time = moment('2014-03-26 10:52:00');
var now = moment();
var value = user_submited_time - now;

Categories