Check if a date is between two dates - javascript

I have an array with different dates with the format of year-month-day.
something like this:
var dates = ["2016-08-01", "2016-08-09", "2016-08-10", ....];
I also have a function that formats todays date in the same format as above. And is stored in a variable:
var currentDate; //Contains current date in the format of year-month-day
What i need to do is to check if any of the dates in the array, either:
Match with today's date.- e.g. Today would be 2016-08-13
Match with 14 days back from today's date. - e.g. 14 days back from today (2016-08-13) would be 2016-07-30
Or match with any dates between the current and 14 days back.
I'm trying to do this by looping through the array, checking each value. But im unsure about the if condition/conditions
for(var i = 0; i < dates.length; i++) {
if(currentDate === *condition*) {
sendDate(dates[i]);
}
}
Anyone have a good solution for this? Thanks in advance!

Firstly, create a new Date() from your currentDate ( currentDate is string format Y-d-m with hour and minutes is 00:00)
var current = new Date(currentDate);
var matchWithCurrent = [];
var matchWithDayBack = [];
var between = [];
just loop through your date array
for (var i=0; i<dates.length; i++) {
var tmpDate = new Date(dates[i]); //Convert string to date
var diff = Math.ceil((current - tmpDate) / (1000 * 3600 * 24)); //get time difference (current - tmpDate is milisecond, we need convert it to day)
// Check condition and push it on array correct
if (diff == 0) {
matchWithCurrent.push(dates[i]);
}
if (diff == 14) {
matchWithDayBack.push(dates[i]);
}
if ((diff > 0) && (diff <14)) {
between.push(dates[i]);
}
}
console.log(matchWithCurrent);
console.log(matchWithDayBack);
console.log(between);
If you want only one array match with 3 condition just check 3 condition in only one if and push it into your result array

One way would be to parse the dates to millisecond values and compare them.
var todayParts = currentDate.split('-');
var today = new Date(todayParts[0], todayParts[1], todayParts[2]).getTime();
var otherParts = dates[i].split('-');
var other = new Date(otherParts[0], otherParts[1], otherParts[2]).getTime();
if (today < other + 1209600000 /* 2 weeks in milliseconds */) {
// The other date is less than 2 weeks before today
}
You can read here why I parsed it manually instead of using Date.parse().

You can compare two dates something like that:
var currentDate = new Date();
for(var i = 0; i < dates.length; i++) {<br>
var arrDate = new Date(dates[i]);
if(currentDate == arrDate)
{//compare array dates with current date
//your code here
}
var beforeDate = (currentDate.getDate() - 14); //14 days before
if(arrDate >= beforeDate && arrDate <= currentDate){
//compare dates between current date and 14 days before date
}
}

Related

How to manipulate date using Javascript

How can I achieve this sequence of date output if the user input is 04-29-2022 and the output is like this
What I want:
2022-05-14
2022-05-29
2022-06-14
2022-06-29
2022-07-14
2022-07-29
2022-08-14
2022-08-29
my code output
2022-05-13
2022-05-28
2022-06-12
2022-06-27
2022-07-12
2022-07-27
2022-08-11
2022-08-26
var dateRelease = new Date("04-29-2022")
const terms = 8
for (let i = 0; i < terms; i++) {
console.log(new Date(dateRelease.setDate(dateRelease.getDate() + 15)).toISOString().slice(0, 10))
}
Here is a function that takes the day of the month in the given date and determines which other date of the month would be needed in the output (either 15 more or 15 less). Then it generates dates alternating between those two date-of-the-month, and when it is the lesser of those two, incrementing the month. In case a date is invalid and automatically overflows into the next month, it is corrected to the last day of the intended month.
To format the date in the output, it is better to not use toISODateString as that interprets the date as a UTC Date, while new Date("2022-04-29") interprets the given string as a date in the local time zone. This can lead to surprises in some time zones. So I would suggest using toLocaleDateString with a locale that produces your desired format.
Here is the code:
function createSchedule(date, count) {
date = new Date(date);
let day = date.getDate();
let k = +(day > 15);
let days = k ? [day - 15, day] : [day, day + 15];
let result = [];
for (let i = 0; i < count; i++) {
k = 1 - k;
date.setDate(days[k]);
// When date overflows into next month, take last day of month
if (date.getDate() !== days[k]) date.setDate(0);
if (!k) date.setMonth(date.getMonth() + 1);
result.push(date.toLocaleDateString("en-SE"));
}
return result;
}
var dateRelease = new Date("2022-04-29");
var result = createSchedule(dateRelease, 25);
console.log(result);
var dateRelease = new Date("04-29-2022")
const terms = 8
for (let i = 0; i < terms; i++) {
let date = new Date(dateRelease.setDate(dateRelease.getDate() + 15)).toLocaleDateString('en-US');
let format = date.split('/').map(d => d.padStart(2 ,'0')).join('-')
console.log(format);
}

Given an ISO date, get the days of the week in form of ISO string ranges

Suppose I have an ISO date, such as 2021-09-18T20:18:27.000Z
I would like to get the dates of the past week in form of an array
The array should be a set of arrays that have two ISO dates that represent the start of the day and the end of the day as illustrated below:
E.g.
input:
2021-09-18T20:18:27.000Z
output:
[
['"2021-09-11T00:00:00.000Z', '"2021-09-11T23:59:59.000Z'],
['"2021-09-12T00:00:00.000Z', '"2021-09-11T23:59:59.000Z'],
['"2021-09-13T00:00:00.000Z', '"2021-09-11T23:59:59.000Z'],
['"2021-09-14T00:00:00.000Z', '"2021-09-11T23:59:59.000Z'],
['"2021-09-15T00:00:00.000Z', '"2021-09-11T23:59:59.000Z'],
['"2021-09-16T00:00:00.000Z', '"2021-09-11T23:59:59.000Z'],
['"2021-09-17T00:00:00.000Z', '"2021-09-11T23:59:59.000Z'],
['"2021-09-18T00:00:00.000Z', '"2021-09-18T23:59:59.000Z'],
]
I've already tried it with dayjs, this results in the array representing exact intervals from a particular date:
function getDates(date) {
var dates = [date]
var noOfDays = 7
for (let i = noOfDays - 1; i >= 0; i--) {
const elementIndex = i - noOfDays // Get last nth element of the list
const dateToIncrement = dates.slice(elementIndex)[0]
const newDate = dayjs(dateToIncrement).subtract(1, "day").toISOString()
dates.unshift(newDate)
}
return dates
}
Thank you
function getPastWeek(inputTime) {
var res = []; //result array
var currentDayEnd = undefined; //variable to be set on each iteration
var currentDay = new Date(inputTime.split('T')[0]); //create new Date object
currentDay.setDate(currentDay.getDate() - 7); //reduce seven days from current date
for(var i = 0; i <= 7; i++) { //foreach day in last week
currentDayEnd = new Date(currentDay.getTime() - 1000); //previous day end (1sec before current day start)
currentDayEnd.setDate(currentDayEnd.getDate() + 1); //current day end (one day after previous day end)
res.push([currentDay.toISOString(), currentDayEnd.toISOString()]); //append pair
currentDay.setDate(currentDay.getDate() + 1); //set variable to next day
}
return res;
}
var pastWeek = getPastWeek('2021-09-18T20:18:27.000Z'); //call example
The OP code is pretty close, you should have been able to adapt it to your needs. The following employs a similar algorithm. End of day is set to 1ms before midnight.
// Given a UTC ISO 8601 timestamp, return array of day plus
// previous 6 days with start of day, end of day timestmaps
function getDates(d) {
let s = new Date(d.slice(0,10));
let e = new Date(+s);
e.setUTCHours(23,59,59,999);
let result = [];
for (let i=7; i; i--) {
result.push([s.toISOString(), e.toISOString()]);
s.setUTCDate(s.getUTCDate() - 1);
e.setUTCDate(e.getUTCDate() - 1);
}
return result;
}
console.log(getDates(new Date().toISOString()));

How to check if date is 3 days before current date

I have this Javascript code, where I have a condition for 3 days after the current date and one for the current day. I would need to add a condition for 3 days previous to the current date. How can I do that?
$('.entry-date').each(function() {
var dateString = $(this).text();
var parts = dateString.split("-");
var date = new Date(parseInt(parts[2]), parseInt(parts[1])-1, parts[0]);
var now = new Date();
var diff = dateDiffInDays(now, date);
if ((diff < 3) && (diff > 0)) {
$(this).parent().addClass("new-entry");
}
if (diff == 0) {
$(this).parent().addClass("today");
}
});

NetSuite - excluding weekends from date calculation

My scheduled script sets a field to store an accrued late fee charge for each day an invoice is overdue. I am comparing the current system time against due date to work out the number of days overdue. However, I didn't take into consideration to exclude the weekend. How can I use my existing code to do this?
var current_date = nlapiStringToDate(nlapiDateToString(new Date()));
var dd = invoice.getFieldValue('duedate');
var due_date = nlapiStringToDate(dd);
if (due_date < current_date) {
//Other Calculations
var days_overdue = DateOverdue(current_date, due_date);
}
function DateOverdue(current_date, due_date) {
var time_difference = Math.abs(due_date.getTime() - current_date.getTime());
var no_days_overdue_by = Math.ceil(time_difference / (1000 * 3600 * 24));
return no_days_overdue_by;
}
The following works. Note the extra dates are to clear issues from comparing time stamps without hours, minutes and seconds. Not strictly needed for the current_date given how you are generating it but it makes a more general function.
NOTE: I don't believe you should be able to compare dates with d1 < d2.
function daysOverdue(currentDate, dueDate){
var days = 0;
var due = new Date(dueDate.getFullYear(), dueDate.getMonth(), dueDate.getDate(), 0, 0, 0);
var fromTS = new Date(currentDate.getFullYear(), currentDate.getMonth(), currentDate.getDate(), 0, 0, 0).getTime();
if(due.getTime() >= fromTS) return 0; // not overdue
while(due.getTime() < fromTS){
if(due.getDay() !== 0 && due.getDay() != 6) days++;
due.setDate(due.getDate() + 1);
}
return days;
}

Only show data on html page where javascript date is within last 10 days

I have javascript array in which the date coming in is in this format
2015-11-25T17:54:19.033
However, I am not really concerned with the time
so I end up with
11/25/15
What I want to do in my loop is to LOOK at the date ( either 2015-11-25T17:54:19.033 or 11/25/15 , whatever is easier) and just set a variable to "NEW" if it is within the last 10 days
I was attempted to play around with this code and it does not give me what I want at all
var dt = "11/25/15";
var today = new Date()
var priorDate = new Date().setDate(today.getDate()-10)
console.log(dt);
console.log(today);
console.log(priorDate);
pseudo code of what i WANT
if ( dt <= today ) {
x = "NEW";
}
So my thoughts are that it need to be in Date objects in javascript but i'm not sure
Update
So say in a loop i have these variables that occur
for ....
dt = 9/13/15
Output = 9/13/15
next time in loop
dt = 11/24/15
Output = NEW - 11/24/15
Working jsfiddle
http://jsfiddle.net/bthorn/yr009hwd/
You are correct. You need to convert the string date to a date time object in javascript to do the comparison.In order to do the comparison, you need to get the millisec of the dates using getTime()
var dt = new Date("11/22/2015");
var today = new Date();
if ( dt.getTime() < today.getTime() ) {
alert('Past');
}
else
alert('future');
To check if the date difference is within 10 days:
var dt = new Date("11/12/2015");
var today = new Date();
var dateDiffDays = Math.ceil((Math.ceil(dt.getTime() - today.getTime()))/(1000 * 3600 * 24));
if( dateDiffDays >= -10 && dateDiffDays <= 10)
alert('date within 10 days');
Depending on the format of your date string, you can probably just do:
var dateToTest = new Date(dt);
//get 10 days earlier
dateToTest.setDate(dateToTest.getDate() - 10);
var today = new Date();
if ( dateToTest < today ) {
x = 'NEW';
}
//see if a date is within the last 10 days
var tenDaysAgo = new Date(); //current date
tenDaysAgo.setDate(tenDaysAgo.getDate() - 10); //ten days ago
//if you don't care about the time
tenDaysAgo.setHours(0);
tenDaysAgo.setMinutes(0);
tenDaysAgo.setSeconds(0);
tenDaysAgo.setMilliseconds(0);
var someDateToTest = new Date('11-1-2015');
if (tenDaysAgo > someDateToTest) {
//this is new
x = 'NEW';
}

Categories

Resources