Creating an array of dates between 2 dates - javascript

I have 2 dates: startdate and enddate. End date is always a day less than the startdate. So if my start day is 19th, the end date would be on the 18th of next month.
I am trying to create an array of number of days in between the 2 dates.
(It goes from 19th to 18th and then 18th to 18th of every month to calculate the difference)
Example
8/19/2018 - 9/18/2018 = 30 days
9/18/2018 - 10/18/2019 = 30 days
10/18/2018 - 11/18/2018 = 31 days
array = [30,30,31]
I am using the following code to calculate days difference between the dates.
function daysBetweenArrears (date1, date2){
date1.setDate(date1.getDate() );
date2.setDate(date2.getDate() - 1);
var Diff = Math.abs(date2.getTime() - date1.getTime());
var TimeDifference = Math.round(Diff / (1000 * 3600 * 24));
return TimeDifference;
}
The following code for creating the array
if (document.getElementById("endDate"))
y = document.getElementById("endDate").value;
if (document.getElementById("startDate"))
z = document.getElementById("startDate").value;
var dateArr = getDateArray(z, y);
var dayCountArr = "";
var b = [];
for (var x = 0; x < dateArr.length-1; x++)
{
dayCountArr += daysBetweenArrears(dateArr[x], dateArr[x+1], ",");
b.push(daysBetweenArrears(dateArr[x], dateArr[x+1]));
}
The issue is that when i set the date as following, it is giving me incorrect output. The problem is that it is setting the dates incorrectly whenever it goes to the next month. I am not sure what i am doing wrong here. Any help is greatly appreciated. Thank you.
date2.setDate(date2.getDate() - 1);

You can do this using moment. Hope this helps.
const start = "8/19/2018";
const end = "11/18/2018 ";
const dates = [];
const mstart = moment(new Date(start));
const mend = moment(new Date(end));
for (let i = 0; mstart < mend ; i++) {
const daysInMonth = mstart.daysInMonth() + (i === 0 ? -1 : 0);
dates.push(daysInMonth);
mstart.add(1, 'M');
}
console.log(dates);
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.22.2/moment.min.js"></script>

You can update your function daysBetweenArrears
const daysBetweenArrears = (date1, date2) => {
const time1 = new Date(date1).getTime();
const time2 = new Date(date2).getTime();
const diff = Math.abs(time2 - time1);
return Math.round(diff/(1000*60*60*24));
};
console.log(daysBetweenArrears('8/18/2018', '9/18/2018'));
console.log(daysBetweenArrears('6/18/2018', '7/18/2018'));

Related

How to find the days of the week in JavaScript

I am trying to find the weekdays from today to Sunday. Since today is Monday I want to display the dates from Monday till Sunday, but tomorrow, I want my programme works from Tuesday to Sunday.
dateSets() {
let firstDayOfWeek = "";
let dates = [];
firstDayOfWeek = new Date();
let sunday = new Date();
sunday.setDate(sunday.getDate() - sunday.getDay() + 7);
const diff = sunday.getDate() - firstDayOfWeek.getDate();
dates.push(new Date());
for (let i = 0; i < diff; i++) {
dates.push(
new Date(firstDayOfWeek.setDate(firstDayOfWeek.getDate() + 1))
);
}
return dates;
},
And here is the other function to find the date of the week:
getDateOfWeek(week, year) {
let simple = new Date(year, 0, 1 + (week - 1) * 7);
let dow = simple.getDay();
let weekStart = simple;
if (dow <= 4) weekStart.setDate(simple.getDate() - simple.getDay() + 1);
else weekStart.setDate(simple.getDate() + 8 - simple.getDay());
return weekStart;
},
But it doesn't work that I expected, in dataset, only Monday is being displayed but not other dates and I don't understand the reason. If you can help me with this, I would be really glad.
Thanks...
function getWeekDates(){
const dates = [new Date()]; // today
const curr = new Date();
const remDaysCount = 7-curr.getDay();
for(let i=1; i<= remDaysCount; i++){
// increase current Date by 1 and set to current Date
const nextDate = curr.setDate(curr.getDate()+1);
dates.push(new Date(nextDate));
}
return dates;
}
console.log(getWeekDates());
This is kind of your choice but if you install NodeJS and open your folder in cmd and type in 'npm init' and 'npm I days' and open your editor and type in
var days = require('days');
console.log(days); // ["Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday"]
console will reveal all of the days of the week and if you want a specific day you can do the following
var days = require('days');
console.log(days[0]); //Sunday
if you need help with installing NodeJS watch a YouTube video or reply to this comment I will help
let firstDayOfWeek = "";
let dates = [];
firstDayOfWeek = new Date();
let sunday = new Date();
sunday.setDate(sunday.getDate() - sunday.getDay() + 7);
//const diff = sunday.getDate() - firstDayOfWeek.getDate();
//Try this code
var timeDiff = Math.abs(sunday.getTime() - firstDayOfWeek.getTime());
var diff = Math.ceil(timeDiff / (1000 * 3600 * 24));
dates.push(new Date());
for (let i = 0; i < diff; i++) {
dates.push(
new Date(firstDayOfWeek.setDate(firstDayOfWeek.getDate() + 1))
);
}
return dates;
Your issue is here:
const diff = sunday.getDate() - firstDayOfWeek.getDate()
Currently the date is 27 Sep and next Sunday is 3 Oct so diff is -4 and the for loop test i < diff is false from the start. Consider using a loop and increment the date from today until it gets to Sunday.
function getDaysToSunday(date = new Date()) {
let d = new Date(+date);
let result = [];
do {
result.push(new Date(+d));
d.setDate(d.getDate() + 1);
} while (d.getDay() != 1)
return result;
}
console.log(getDaysToSunday().map(d=>d.toDateString()));

Converting date array with getTime()

this is a snippet of code from a project I am doing, I have to convert dates using to getTime() function and push them into a new array, however everytime i do however the new array prints as NaN, i was hoping to gain some insight on what i was doing wrong and how to fix this issue. Thanks a ton :)
dates = ["28/7/2020", "28/3/2020", "28/1/2020", "28/10/2020"]
// const MAX = dates[0]
// const MIN = dates[dates.length - 1];
const dateArr = [];
const DAY_IN_MS = 24 * 60 * 60 * 1000
for (i = 0; i < dates.length; i++) {
d = new Date(dates[i])
dateInMs = d.getTime();
parseInt(dateInMs);
console.log(dateInMs);
dateArr.push(dateInMs);
}
<!DOCTYPE html>
<html lang="en">
<head>
</head>
<body>
</body>
</html>
you have to switch the day and month otherwise new Date will return invalid date
example:
const d = "28/7/2020";
const dateSplit = d.split("/")
new Date(`${dateSplit[1]}/${dateSplit[0]}/${dateSplit[2]}`)
will return: Tue Jul 28 2020 00:00:00 GMT+0200 (Central European Summer Time)
What you could do is replace your New date line with the following:
const dateSplit = dates[i].split("/")
const newDate = new Date(`${dateSplit[1]}/${dateSplit[0]}/${dateSplit[2]}`)
d = new Date(newDate)
Either that or try to change the initial format to something new Date can Handle. This will prevent of having to split and add extra code
EDIT: To get the amount of days between first and last date. Here is an example:
const minutes = 1000*60;
const hours = minutes*60;
const days = hours*24;
const date1 = new Date("7/28/2020").getTime();
const date2 = new Date("10/28/2020").getTime();
const dateDiff = Math.round((date2 - date1)/days);
console.log(dateDiff);
EDIT 2: to get the difference in length you would do this (using the dates you mentioned in your comment):
const dateArr = [];
let date1 = ("23/9/2020").split("/");
let date2 = ("29/9/2020").split("/");
const diffDays = date2[0] - date1[0]; // date1[0] = 23, date2[0] = 29
for (i = 0; i <= diffDays; i++) {
// content of the push would save each day between 23 and 29 as value... you can put whatever in here
dateArr.push(`${date1[0] + i}/9/2020`);
}
console.log(dateArr.length); // should equal 7
3 lines in your javascript code are missing semicolons. My suggestion is to review your code a bit more carefully before posting, and also review the syntax for the various javascript date functions. This should work:
const dates = ["28/7/2020", "28/3/2020", "28/1/2020", "28/10/2020"];
var dateArr = [];
var DAY_IN_MS = 24 * 60 * 60 * 1000;
for (i = 0; i < dates.length; i++) {
// format your date string properly for Date()
var tmp = dates[i].split('/');
// convert the string to a date
var d = new Date( tmp[2], tmp[1], tmp[0] );
console.log( dates[i] );
console.log( d );
dateInMs = d.getTime();
parseInt(dateInMs);
console.log(dateInMs);
dateArr.push(dateInMs);
}

Create array of dates from starting date in JavaScript and React

I have a React component where I have a date string from which I need to generate an array of dates representing the next 11 days excluding the starting date (10/12/2016). Not sure how to achieve this. That's what I've tried so far but the problem is that by simply looping adding 1 for each iteration on the day, it won't generate the correct date when the date range of 11 days spans between two months:
addDays = () => {
const { startDate } = this.props.pageData.parcelDetails.parcelDetails;
const date = new Date(startDate);
let datesCollection = []
for (var i = 1; i < 12; i++) {
datesCollection.push(`${date.getDate() + i}/${date.getMonth() + 1}/${date.getFullYear()}`)
}
return datesCollection
}
The code above generates the following array:
[
"11/12/2016",
"12/12/2016",
"13/12/2016",
"14/12/2016",
"15/12/2016",
"16/12/2016",
"17/12/2016",
"18/12/2016",
"19/11/2016",
"20/12/2016",
"21/12/2016"
]
How do I generate the correct array, with proper dates for each month?
You can simply do that:
addDays = () => {
const { startDate } = this.props.pageData.parcelDetails.parcelDetails;
const date = new Date(startDate);
let datesCollection = []
for (var i = 1; i < 12; i++) {
const newDate = new Date(date.getTime() + i * 1000 * 60 * 60 * 24);
datesCollection.push(`${newDate.getDate()}/${newDate.getMonth() + 1}/${newDate.getFullYear()}`);
}
return datesCollection
}
You can try adding 1 day to each loop.
var dateuse = new Date();
dateuse.setDate(dateuse.getDate() + 1);
or you can try Moment.js
var today = moment();
var dateuse = moment(today).add(1, 'days');

How can I use moment.js to add days, excluding weekends?

I'm setting a default follow-up date two days from current date, which currently works:
const Notify = moment().add(2, 'days').toDate();
However, I would like to exclude weekends. So I installed moment WeekDay, but I can't seem to get it to work with adding days to the current date. The documentation calls for:
moment().weekday(0)
But I can't get that to work with adding in two days forward. Any ideas?
This solution is simple, easy to follow, and works well for me:
function addBusinessDays(originalDate, numDaysToAdd) {
const Sunday = 0;
const Saturday = 6;
let daysRemaining = numDaysToAdd;
const newDate = originalDate.clone();
while (daysRemaining > 0) {
newDate.add(1, 'days');
if (newDate.day() !== Sunday && newDate.day() !== Saturday) {
daysRemaining--;
}
}
return newDate;
}
Try: moment-business-days
It should help you.
Example:
var momentBusinessDays = require("moment-business-days")
momentBusinessDays('20-09-2018', 'DD-MM-YYYY').businessAdd(3)._d
Result:
Tue Sep 25 2018 00:00:00 GMT+0530 (IST)
You could also not use external lib and do a simple function like one of these two:
const WEEKEND = [moment().day("Saturday").weekday(), moment().day("Sunday").weekday()]
const addBusinessDays1 = (date, daysToAdd) => {
var daysAdded = 0,
momentDate = moment(new Date(date));
while (daysAdded < daysToAdd) {
momentDate = momentDate.add(1, 'days');
if (!WEEKEND.includes(momentDate.weekday())) {
daysAdded++
}
}
return momentDate;
}
console.log(addBusinessDays1(new Date(), 7).format('MM/DD/YYYY'))
console.log(addBusinessDays1('09-20-2018', 3).format('MM/DD/YYYY'))
// This is the somewhat faster version
const addBusinessDays2 = (date, days) => {
var d = moment(new Date(date)).add(Math.floor(days / 5) * 7, 'd');
var remaining = days % 5;
while (remaining) {
d.add(1, 'd');
if (d.day() !== 0 && d.day() !== 6)
remaining--;
}
return d;
};
console.log(addBusinessDays2(new Date(), 7).format('MM/DD/YYYY'))
console.log(addBusinessDays2('09-20-2018', 3).format('MM/DD/YYYY'))
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.22.2/moment.min.js"></script>
They are slightly modified from this post and I think are a good alternative to external library you have to carry/deal with (assuming this is the only part you need and not other features of that lib).
This will do it based on any starting date, and without a costly loop. You calculate the number of weekend days you need to skip over, then just offset by the number of weekdays and weekends, together.
function addWeekdays(year, month, day, numberOfWeekdays) {
var originalDate = year + '-' + month + '-' + day;
var futureDate = moment(originalDate);
var currentDayOfWeek = futureDate.day(); // 0 = Sunday, 1 = Monday, ..., 6 = Saturday
var numberOfWeekends = Math.floor((currentDayOfWeek + numberOfWeekdays - 1) / 5); // calculate the number of weekends to skip over
futureDate.add(numberOfWeekdays + numberOfWeekends * 2, 'days'); // account for the 2 days per weekend
return futureDate;
}
const addWorkingDays = (date: Moment, days: number) => {
let newDate = date.clone();
for (let i = 0; i < days; i++) {
if (newDate.isoWeekday() !== 6 && newDate.isoWeekday() !== 7) {
newDate = newDate.add(1, "days");
} else {
newDate = newDate.add(1, "days");
i--;
}
}
return newDate.format("YYYY/MM/DD");
};
var moment = require("moment")
function addWorkingDay(date, days){
let daysToAdd = days
const today = moment(date);
const nextWeekStart = today.clone().add(1, 'week').weekday(1);
const weekEnd = today.clone().weekday(5);
const daysTillWeekEnd = Math.max(0, weekEnd.diff(today, 'days'));
if(daysTillWeekEnd >= daysToAdd) return today.clone().add(daysToAdd, 'days');
daysToAdd = daysToAdd - daysTillWeekEnd - 1;
return nextWeekStart.add(Math.floor(daysToAdd/5), 'week').add(daysToAdd % 5, 'days')
}
I think this code will be faster:
var businessDays = 10;
var days = businessDays + Math.floor((Math.min(moment().day(),5)+businessDays)/6)*2;
moment.add(days, 'days');
// using pure JS
function addBusinessDays(originalDate, numDaysToAdd) {
const Sunday = 0;
const Saturday = 6;
let daysRemaining = numDaysToAdd;
const newDate = originalDate;
while (daysRemaining > 0) {
newDate.setDate(newDate.getDate() + 1);
if (newDate.getDay() !== 0 && newDate.getDay() !== 6) {
// skip sunday & saturday
daysRemaining--;
}
}
return newDate;
}
var dt = new Date(); // get date
var business_days = 8;
newDate = addBusinessDays(dt, business_days);
console.log(newDate.toString());

How to check if the date having more than one year from current year

I am trying to check if the date i.e. (07/02/2018 ) is more than year from current date and if the date i.e. (07/02/2018 ) is less than year from current date using JavaScript tried with following code
var x = new Date('JUN-2016');
var y = new Date('MAY-2016');
console.log(+x < +y);
Your question is not very clear to me but this may help you:
var now = new Date();
var then = new Date('07/02/2018');
var diffInDays = Math.round((then-now) / (1000*60*60*24));
console.log('then is', diffInDays, 'days more than now.');
Note: If diffInDays is a positive number then the then is more than now, otherwise it's less.
You can simply add 1000*60*60*24*365 milliseconds to your first date and compare it to your second date :
var x = new Date('APR-2015');
var y = new Date('MAY-2016');
console.log(+x + 1000*60*60*24*365 < +y);
var x2 = new Date('SEP-2015');
console.log(+x2 + 1000*60*60*24*365 < +y);
You can get the year with the getFullYear()method (Date doc).
let x = new Date();
let y = new Date();
x_year = x.getFullYear();
y_year = y.getFullYear();
// The you just have to compare the year
One way to do it, although I'd be surprised if there wasn't a better way:
var x = new Date();
x = x.setFullYear(x.getFullYear() + 1);
x = new Date(x);
var y = (new Date('2018-04-08'));
var z = (new Date('2019-04-08'));
if (y < x) {
console.log('Y is less than a year from now');
} else {
console.log('Y is more or exactly a year from now');
}
if (z < x) {
console.log('Z is less than a year from now');
} else {
console.log('Z is more or exactly a year from now');
}
Your question is not clear this is based on my assumption.
I am assuming that you need to check if the given date is one year ahead of the current date.
var x = new Date('1, 1, 2018');
var today = new Date();
var time = Math.abs(today.getTime() - x.getTime());
var days = Math.ceil(time / (1000 * 3600 * 24));
alert("There is a difference of " + days + " days between today and the given date");
I am assuming that you want to know if some arbitrary date is less or more than a year from current date.
We can get a the value for a year this way:
var a_year = Math.abs(new Date('01-01-2018'.replace(/-/g,'/')) - new Date('01-01-2017'.replace(/-/g,'/')));
Then we set two date tests:
var test1 = '01-01-2018';
var test2 = '01-01-2015';
Calculate the diffs:
var diff1 = Math.abs(new Date() - new Date(test1.replace(/-/g,'/')));
var diff2 = Math.abs(new Date() - new Date(test2.replace(/-/g,'/')));
Then you can log the results for testing:
console.log(diff1 > a_year)
console.log(diff1 < a_year)
console.log(diff2 > a_year)
console.log(diff2 < a_year)
Credits to David Hedlund's answer on How to subtract date/time in javascript?

Categories

Resources