How to check if date is 3 days before current date - javascript

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");
}
});

Related

Show next date while skipping holidays in javascript [duplicate]

I have a javascript function which is calculating working days between 2 dates, it works, but the problem is that it not consider holidays. How can I modify this function, for example by adding holidays in exception array?
Searched in internet about this question, but haven't find about holidays exception.
For example holidays array:
var holidays = ['2016-05-03','2016-05-05'];
And I have a functions to calculate this:
function workingDaysBetweenDates(d0, d1) {
var startDate = parseDate(d0);
var endDate = parseDate(d1);
// Validate input
if (endDate < startDate)
return 0;
// Calculate days between dates
var millisecondsPerDay = 86400 * 1000; // Day in milliseconds
startDate.setHours(0,0,0,1); // Start just after midnight
endDate.setHours(23,59,59,999); // End just before midnight
var diff = endDate - startDate; // Milliseconds between datetime objects
var days = Math.ceil(diff / millisecondsPerDay);
// Subtract two weekend days for every week in between
var weeks = Math.floor(days / 7);
days = days - (weeks * 2);
// Handle special cases
var startDay = startDate.getDay();
var endDay = endDate.getDay();
// Remove weekend not previously removed.
if (startDay - endDay > 1)
days = days - 2;
// Remove start day if span starts on Sunday but ends before Saturday
if (startDay == 0 && endDay != 6)
days = days - 1
// Remove end day if span ends on Saturday but starts after Sunday
if (endDay == 6 && startDay != 0)
days = days - 1
return days;
}
function parseDate(input) {
// Transform date from text to date
var parts = input.match(/(\d+)/g);
// new Date(year, month [, date [, hours[, minutes[, seconds[, ms]]]]])
return new Date(parts[0], parts[1]-1, parts[2]); // months are 0-based
}
Have made an example in jsfiddle:
JSFiddle example
Maybe there are some other functions which can easy use in Jquery?
Try:
var startDate = new Date('05/03/2016');
var endDate = new Date('05/10/2016');
var numOfDates = getBusinessDatesCount(startDate,endDate);
function getBusinessDatesCount(startDate, endDate) {
let count = 0;
const curDate = new Date(startDate.getTime());
while (curDate <= endDate) {
const dayOfWeek = curDate.getDay();
if(dayOfWeek !== 0 && dayOfWeek !== 6) count++;
curDate.setDate(curDate.getDate() + 1);
}
alert(count);
return count;
}
The easiest way to achieve it is looking for these days between your begin and end date.
Edit: I added an additional verification to make sure that only working days from holidays array are subtracted.
$(document).ready(() => {
$('#calc').click(() => {
var d1 = $('#d1').val();
var d2 = $('#d2').val();
$('#dif').text(workingDaysBetweenDates(d1,d2));
});
});
let workingDaysBetweenDates = (d0, d1) => {
/* Two working days and an sunday (not working day) */
var holidays = ['2016-05-03', '2016-05-05', '2016-05-07'];
var startDate = parseDate(d0);
var endDate = parseDate(d1);
// Validate input
if (endDate <= startDate) {
return 0;
}
// Calculate days between dates
var millisecondsPerDay = 86400 * 1000; // Day in milliseconds
startDate.setHours(0, 0, 0, 1); // Start just after midnight
endDate.setHours(23, 59, 59, 999); // End just before midnight
var diff = endDate - startDate; // Milliseconds between datetime objects
var days = Math.ceil(diff / millisecondsPerDay);
// Subtract two weekend days for every week in between
var weeks = Math.floor(days / 7);
days -= weeks * 2;
// Handle special cases
var startDay = startDate.getDay();
var endDay = endDate.getDay();
// Remove weekend not previously removed.
if (startDay - endDay > 1) {
days -= 2;
}
// Remove start day if span starts on Sunday but ends before Saturday
if (startDay == 0 && endDay != 6) {
days--;
}
// Remove end day if span ends on Saturday but starts after Sunday
if (endDay == 6 && startDay != 0) {
days--;
}
/* Here is the code */
holidays.forEach(day => {
if ((day >= d0) && (day <= d1)) {
/* If it is not saturday (6) or sunday (0), substract it */
if ((parseDate(day).getDay() % 6) != 0) {
days--;
}
}
});
return days;
}
function parseDate(input) {
// Transform date from text to date
var parts = input.match(/(\d+)/g);
// new Date(year, month [, date [, hours[, minutes[, seconds[, ms]]]]])
return new Date(parts[0], parts[1]-1, parts[2]); // months are 0-based
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="text" id="d1" value="2016-05-02"><br>
<input type="text" id="d2" value="2016-05-08">
<p>Working days count: <span id="dif"></span></p>
<button id="calc">Calc</button>
<p>
Now it shows 5 days, but I need for example add holidays
3 and 5 May (2016-05-03 and 2016-05-05) so the result will be 3 working days
</p>
I took a similar approach to #OscarGarcia mainly as an excercise since my JS is rusty.
While it looks similar, it takes care not to substract a day twice if a holiday happens to be on a saturday or sunday. This way, you can pre-load a list of recurring dates (such as Dec 25th, Jan 1st, July 4th, which may or may not be on an otherwise working day -monday thru friday-)
$(document).ready(function(){
$('#calc').click(function(){
var d1 = $('#d1').val();
var d2 = $('#d2').val();
$('#dif').text(workingDaysBetweenDates(d1,d2));
});
});
function workingDaysBetweenDates(d0, d1) {
var startDate = parseDate(d0);
var endDate = parseDate(d1);
// populate the holidays array with all required dates without first taking care of what day of the week they happen
var holidays = ['2018-12-09', '2018-12-10', '2018-12-24', '2018-12-31'];
// Validate input
if (endDate < startDate)
return 0;
var z = 0; // number of days to substract at the very end
for (i = 0; i < holidays.length; i++)
{
var cand = parseDate(holidays[i]);
var candDay = cand.getDay();
if (cand >= startDate && cand <= endDate && candDay != 0 && candDay != 6)
{
// we'll only substract the date if it is between the start or end dates AND it isn't already a saturday or sunday
z++;
}
}
// Calculate days between dates
var millisecondsPerDay = 86400 * 1000; // Day in milliseconds
startDate.setHours(0,0,0,1); // Start just after midnight
endDate.setHours(23,59,59,999); // End just before midnight
var diff = endDate - startDate; // Milliseconds between datetime objects
var days = Math.ceil(diff / millisecondsPerDay);
// Subtract two weekend days for every week in between
var weeks = Math.floor(days / 7);
days = days - (weeks * 2);
// Handle special cases
var startDay = startDate.getDay();
var endDay = endDate.getDay();
// Remove weekend not previously removed.
if (startDay - endDay > 1)
days = days - 2;
// Remove start day if span starts on Sunday but ends before Saturday
if (startDay == 0 && endDay != 6)
days = days - 1
// Remove end day if span ends on Saturday but starts after Sunday
if (endDay == 6 && startDay != 0)
days = days - 1
// substract the holiday dates from the original calculation and return to the DOM
return days - z;
}
function parseDate(input) {
// Transform date from text to date
var parts = input.match(/(\d+)/g);
// new Date(year, month [, date [, hours[, minutes[, seconds[, ms]]]]])
return new Date(parts[0], parts[1]-1, parts[2]); // months are 0-based
}
2018-12-09 is a sunday... with this code, it'll only be substracted once (for being a sunday) and not twice (as it would if we only checked if its a national holiday)
I think this solution is much more simpler
const numberOfDaysInclusive = (d0, d1) => {
return 1 + Math.round((d1.getTime()-d0.getTime())/(24*3600*1000));
}
const numberOfWeekends = (d0, d1) => {
const days = numberOfDaysInclusive(d0, d1); // total number of days
const sundays = Math.floor((days + (d0.getDay() + 6) % 7) / 7); // number of sundays
return 2*sundays + (d1.getDay()==6) - (d0.getDay()==0); // multiply sundays by 2 to get both sat and sun, +1 if d1 is saturday, -1 if d0 is sunday
}
const numberOfWeekdays = (d0, d1) => {
return numberOfDaysInclusive(d0, d1) - numberOfWeekends(d0, d1);
}
Get all weekdays between two dates:
private getCorrectWeekDays(StartDate,EndDate){
let _weekdays = [0,1,2,3,4];
var wdArr= [];
var currentDate = StartDate;
while (currentDate <= EndDate) {
if ( _weekdays.includes(currentDate.getDay())){
wdArr.push(currentDate);
//if you want to format it to yyyy-mm-dd
//wdArr.push(currentDate.toISOString().split('T')[0]);
}
currentDate.setDate(currentDate.getDate() +1);
}
return wdArr;
}
You can also try this piece of code:
const moment = require('moment-business-days');
/**
*
* #param {String} date - iso Date
* #returns {Number} difference between now and #param date
*/
const calculateDaysLeft = date => {
try {
return moment(date).businessDiff(moment(new Date()))
} catch (err) {
throw new Error(err)
}
}
The top answer actually works but with a flaw.
When the holyday is in a Saturday or Sunday it still reduces a day.
Add this to the existing code:
.... /* Here is the code */
for (var i in holidays) {
if ((holidays[i] >= d0) && (holidays[i] <= d1)) {
// Check if specific holyday is Saturday or Sunday
var yourDate = new Date(holidays[i]);
if(yourDate.getDay() === 6 || yourDate.getDay() === 0){
// If it is.. do nothing
} else {
// if it is not, reduce a day..
days--;
}
}
}
const workday_count = (start, end) => {
start = moment(start).format(("YYYY-MM-DD"))
end = moment(end).format(("YYYY-MM-DD"))
let workday_count = 0;
let totalDays = moment(end).diff(moment(start), "days");
let date = start
for (let i = 1; i <= totalDays; i++) {
if (i == 1) {
date = moment(date)
} else {
date = moment(date).add(1, "d");
}
date = new Date(date);
let dayOfWeek = date.getDay();
let isWeekend = (dayOfWeek === 6) || (dayOfWeek === 0);
if (!isWeekend) {
workday_count = workday_count + 1;
}
}
return workday_count;
}
Simply reduce the length of array from the value you have got (in your fiddle)
var numberofdayswithoutHolidays= 5;
var holidays = ['2016-05-03','2016-05-05'];
alert( numberofdayswithoutHolidays - holidays.length );
You need to filter out weekends from holidays as well
holidays = holidays.filter( function(day){
var day = parseDate( day ).getDay();
return day > 0 && day < 6;
})
$(document).ready(() => {
$('#calc').click(() => {
var d1 = $('#d1').val();
var d2 = $('#d2').val();
$('#dif').text(workingDaysBetweenDates(d1,d2));
});
});
let workingDaysBetweenDates = (d0, d1) => {
/* Two working days and an sunday (not working day) */
var holidays = ['2016-05-03', '2016-05-05', '2016-05-07'];
var startDate = parseDate(d0);
var endDate = parseDate(d1);
// Validate input
if (endDate < startDate) {
return 0;
}
// Calculate days between dates
var millisecondsPerDay = 86400 * 1000; // Day in milliseconds
startDate.setHours(0, 0, 0, 1); // Start just after midnight
endDate.setHours(23, 59, 59, 999); // End just before midnight
var diff = endDate - startDate; // Milliseconds between datetime objects
var days = Math.ceil(diff / millisecondsPerDay);
// Subtract two weekend days for every week in between
var weeks = Math.floor(days / 7);
days -= weeks * 2;
// Handle special cases
var startDay = startDate.getDay();
var endDay = endDate.getDay();
// Remove weekend not previously removed.
if (startDay - endDay > 1) {
days -= 2;
}
// Remove start day if span starts on Sunday but ends before Saturday
if (startDay == 0 && endDay != 6) {
days--;
}
// Remove end day if span ends on Saturday but starts after Sunday
if (endDay == 6 && startDay != 0) {
days--;
}
/* Here is the code */
holidays.forEach(day => {
if ((day >= d0) && (day <= d1)) {
/* If it is not saturday (6) or sunday (0), substract it */
if ((parseDate(day).getDay() % 6) != 0) {
days--;
}
}
});
return days;
}
function parseDate(input) {
// Transform date from text to date
var parts = input.match(/(\d+)/g);
// new Date(year, month [, date [, hours[, minutes[, seconds[, ms]]]]])
return new Date(parts[0], parts[1]-1, parts[2]); // months are 0-based
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="text" id="d1" value="2016-05-02"><br>
<input type="text" id="d2" value="2016-05-08">
<p>Working days count: <span id="dif"></span></p>
<button id="calc">Calc</button>
<p>
Now it shows 5 days, but I need for example add holidays
3 and 5 May (2016-05-03 and 2016-05-05) so the result will be 3 working days
</p>

Convert javascript from single date exclusion to multiple dates

With our limited knowledge we were able to exclude certain dates in a date delivery module based on weekday and time. See code below.
But now we want to exclude all Wednesdays and Saturdays in the next year if you select carrier 99. So multiple disabledDays.push(excldatum) being each Wednesday and Saturday for one year starting from today if this particular carrier is selected.
Can someone please help us how to write that code?
var selected_carrier = parseInt($('.delivery_option_radio:checked').val());
var weekdag = new Date().getDay();
var uur = new Date().getHours();
var vandaag = new Date();
var morgen = new Date();
morgen.setDate(vandaag.getDate() + 1);
var exclmaand = morgen.getMonth() + 1;
var excldag = morgen.getDate();
var excldatum = exclmaand + "-" + excldag;
// carrier is postnl
if (selected_carrier == 99) {
// weekdag 0 is zondag t/m 6 is zaterdag
if (weekdag > -1 && weekdag < 5) {
// na 23 uur
if (uur >= 23) {
disabledDays.push(excldatum);
}
}
}
if (selected_carrier == 99) {
// weekdag 5 is vrijdag
if (weekdag == 5) {
// na 10 uur
if (uur >= 10) {
disabledDays.push(excldatum);
}
}
}
Something like the following piece of code might work for you. It gets all dates for the specified weekdaysToProcess for the next 365 days starting today. Eg. [3,6] for Wednesday and Saturday.
You can add any other filtering you like of course.
function GetDatesForWeekdaysForNext365Days(weekdaysToProcess) {
var currentDate = new Date();
var foundDates = [];
for (var day = 0; day < 365; day++) {
var calculatedDate = new Date();
calculatedDate.setDate(currentDate.getDate() + day);
var calculatedWeekDay = calculatedDate.getDay();
if (weekdaysToProcess.includes(calculatedWeekDay)) {
foundDates.push(calculatedDate);
}
}
return foundDates;
}
The function can be called for carrier 99 like:
disabledDays = GetDatesForWeekdaysForNext365Days([3,6]);

how can i count the range between 2 dates without counting the weekend in javascript

i want to calculate the range between 2 dates without counting weekend in javascript. i have some code that already count the range between them. but i'm stuck with the weekend part. date inputed by CJuiDatePicker in YII framework
<script>
function calcDay(dt1, dt2, range){
var msec1 = dt1;
var date1 = new date(msec1);
var msec2 = dt2;
var date2 = new date(msec2);
if(date1>0 || date2>0){
range.val(isFinite(Math.round(date2-date1)/86400000) || 0);
}
};
</script>
86400000 is day in millisecond
thanks in advance
The function you'll need is getUTCDay().
the pseudo code would be as follows:
1 - determine full weeks (days/7 truncated)
2 - calculate weekday/weekend: 2 * result = weekend days, 5 * result = weekdays.
3 - after that, remainder and starting day of week will determine the 1 or 2 additional days
Hope that helps, let me know if you need the javascript,
- John
Edited, as requested. NOTE: tweaked your original for testing, you should spot the needed changes to restore.
function calcDay(dt1, dt2, range)
{
var msec1 = "October 13, 2014 11:13:00";
var date1 = new Date(msec1);
var msec2 = "October 13, 2013 11:13:00";
var date2 = new Date(msec2);
var days;
var wdays;
var startday;
var nLeft;
// neither should be zero
if(date1>0 && date2>0) {
days = Math.round( Math.abs((date2-date1)/86400000) );
wdays = Math.round(days / 7) * 5;
nLeft = days % 7;
startday = (date1 > date2) ? date2.getUTCDay() : date1.getUTCDay();
if (startday < 2) {
wdays += Math.max(nLeft+startday-1,0);
} else if (startday == 6) {
wdays += Math.max(nLeft-2,0);
} else if (nLeft > (7-startday)) {
wdays += (nLeft-2)
} else {
wdays += Math.min(nLeft, 6-startday)
}
}
};
i found my own solution, but i forgot to share it. this is how i make it
function myUpdate(dt1, dt2,range){
var msec1 = dt1;
var date1 = new Date(msec1);
var msec2 = dt2;
var date2 = new Date(msec2);
var diff = (isFinite(Math.round (date2 - date1) / 86400000) && Math.round (date2 - date1) / 86400000 || 0);
var wEnd=0;
if(date1>0 || date2>0){
for(var i=0; i<=diff; i++){
if(date1.getDay() ==6 || date1.getDay()==0){
wEnd = wEnd + 1;
}
date1.setDate(date1.getDate() + 1);
}
}
range.val(Math.round((diff-wEnd)+1));
};
first u should count the different date, then the date1 will be check if it is sunday or saturday. then date1 will be added 1 till the value of date1 is equal to date2. if date1 is/are saturday or sunday, wEnd will gain 1. so u can substract diff with wEnd. hope this can help u guys

Check if one date is between two dates

I need to check if a date - a string in dd/mm/yyyy format -
falls between two other dates having the same format dd/mm/yyyy
I tried this, but it doesn't work:
var dateFrom = "02/05/2013";
var dateTo = "02/09/2013";
var dateCheck = "02/07/2013";
var from = Date.parse(dateFrom);
var to = Date.parse(dateTo);
var check = Date.parse(dateCheck );
if((check <= to && check >= from))
alert("date contained");
I used debugger and checked, the to and from variables have isNaN value.
Could you help me?
Date.parse supports the format mm/dd/yyyy not dd/mm/yyyy. For the latter, either use a library like moment.js or do something as shown below
var dateFrom = "02/05/2013";
var dateTo = "02/09/2013";
var dateCheck = "02/07/2013";
var d1 = dateFrom.split("/");
var d2 = dateTo.split("/");
var c = dateCheck.split("/");
var from = new Date(d1[2], parseInt(d1[1])-1, d1[0]); // -1 because months are from 0 to 11
var to = new Date(d2[2], parseInt(d2[1])-1, d2[0]);
var check = new Date(c[2], parseInt(c[1])-1, c[0]);
console.log(check > from && check < to)
Instead of comparing the dates directly, compare the getTime() value of the date. The getTime() function returns the number of milliseconds since Jan 1, 1970 as an integer-- should be trivial to determine if one integer falls between two other integers.
Something like
if((check.getTime() <= to.getTime() && check.getTime() >= from.getTime())) alert("date contained");
Try what's below. It will help you...
Fiddle : http://jsfiddle.net/RYh7U/146/
Script :
if(dateCheck("02/05/2013","02/09/2013","02/07/2013"))
alert("Availed");
else
alert("Not Availed");
function dateCheck(from,to,check) {
var fDate,lDate,cDate;
fDate = Date.parse(from);
lDate = Date.parse(to);
cDate = Date.parse(check);
if((cDate <= lDate && cDate >= fDate)) {
return true;
}
return false;
}
The answer that has 50 votes doesn't check for date in only checks for months. That answer is not correct. The code below works.
var dateFrom = "01/08/2017";
var dateTo = "01/10/2017";
var dateCheck = "05/09/2017";
var d1 = dateFrom.split("/");
var d2 = dateTo.split("/");
var c = dateCheck.split("/");
var from = new Date(d1); // -1 because months are from 0 to 11
var to = new Date(d2);
var check = new Date(c);
alert(check > from && check < to);
This is the code posted in another answer and I have changed the dates and that's how I noticed it doesn't work
var dateFrom = "02/05/2013";
var dateTo = "02/09/2013";
var dateCheck = "07/07/2013";
var d1 = dateFrom.split("/");
var d2 = dateTo.split("/");
var c = dateCheck.split("/");
var from = new Date(d1[2], parseInt(d1[1])-1, d1[0]); // -1 because months are from 0 to 11
var to = new Date(d2[2], parseInt(d2[1])-1, d2[0]);
var check = new Date(c[2], parseInt(c[1])-1, c[0]);
alert(check > from && check < to);
Simplified way of doing this based on the accepted answer.
In my case I needed to check if current date (Today) is pithing the range of two other dates so used newDate() instead of hardcoded values but you can get the point how you can use hardcoded dates.
var currentDate = new Date().toJSON().slice(0,10);
var from = new Date('2020/01/01');
var to = new Date('2020/01/31');
var check = new Date(currentDate);
console.log(check > from && check < to);
I have created customize function to validate given date is between two dates or not.
var getvalidDate = function(d){ return new Date(d) }
function validateDateBetweenTwoDates(fromDate,toDate,givenDate){
return getvalidDate(givenDate) <= getvalidDate(toDate) && getvalidDate(givenDate) >= getvalidDate(fromDate);
}
Here is a Date Prototype method written in typescript:
Date.prototype.isBetween = isBetween;
interface Date { isBetween: typeof isBetween }
function isBetween(minDate: Date, maxDate: Date): boolean {
if (!this.getTime) throw new Error('isBetween() was called on a non Date object');
return !minDate ? true : this.getTime() >= minDate.getTime()
&& !maxDate ? true : this.getTime() <= maxDate.getTime();
};
I did the same thing that #Diode, the first answer, but i made the condition with a range of dates, i hope this example going to be useful for someone
e.g (the same code to example with array of dates)
var dateFrom = "02/06/2013";
var dateTo = "02/09/2013";
var d1 = dateFrom.split("/");
var d2 = dateTo.split("/");
var from = new Date(d1[2], parseInt(d1[1])-1, d1[0]); // -1 because months are from 0 to 11
var to = new Date(d2[2], parseInt(d2[1])-1, d2[0]);
var dates= ["02/06/2013", "02/07/2013", "02/08/2013", "02/09/2013", "02/07/2013", "02/10/2013", "02/011/2013"];
dates.forEach(element => {
let parts = element.split("/");
let date= new Date(parts[2], parseInt(parts[1]) - 1, parts[0]);
if (date >= from && date < to) {
console.log('dates in range', date);
}
})
Try this:
HTML
<div id="eventCheck"></div>
JAVASCRIPT
// ----------------------------------------------------//
// Todays date
var today = new Date();
var dd = today.getDate();
var mm = today.getMonth()+1; //January is 0!
var yyyy = today.getFullYear();
// Add Zero if it number is between 0-9
if(dd<10) {
dd = '0'+dd;
}
if(mm<10) {
mm = '0'+mm;
}
var today = yyyy + '' + mm + '' + dd ;
// ----------------------------------------------------//
// Day of event
var endDay = 15; // day 15
var endMonth = 01; // month 01 (January)
var endYear = 2017; // year 2017
// Add Zero if it number is between 0-9
if(endDay<10) {
endDay = '0'+endDay;
}
if(endMonth<10) {
endMonth = '0'+endMonth;
}
// eventDay - date of the event
var eventDay = endYear + '/' + endMonth + '/' + endDay;
// ----------------------------------------------------//
// ----------------------------------------------------//
// check if eventDay has been or not
if ( eventDay < today ) {
document.getElementById('eventCheck').innerHTML += 'Date has passed (event is over)'; // true
} else {
document.getElementById('eventCheck').innerHTML += 'Date has not passed (upcoming event)'; // false
}
Fiddle:
https://jsfiddle.net/zm75cq2a/
Suppose for example your date is coming like this & you need to install momentjs for advance date features.
let cmpDate = Thu Aug 27 2020 00:00:00 GMT+0530 (India Standard Time)
let format = "MM/DD/YYYY";
let startDate: any = moment().format(format);
let endDate: any = moment().add(30, "days").format(format);
let compareDate: any = moment(cmpDate).format(format);
var startDate1 = startDate.split("/");
var startDate2 = endDate.split("/");
var compareDate1 = compareDate.split("/");
var fromDate = new Date(startDate1[2], parseInt(startDate1[1]) - 1, startDate1[0]);
var toDate = new Date(startDate2[2], parseInt(startDate2[1]) - 1, startDate2[0]);
var checkDate = new Date(compareDate1[2], parseInt(compareDate1[1]) - 1, compareDate1[0]);
if (checkDate > fromDate && checkDate < toDate) {
... condition works between current date to next 30 days
}
This may feel a bit more intuitive. The parameter is just a valid date string.
This function returns true if the date passed as argument is in the current week, or false if not.
function isInThisWeek(dateToCheck){
// Create a brand new Date instance
const WEEK = new Date()
// create a date instance with the function parameter
//(format should be like dd/mm/yyyy or any javascript valid date format )
const DATEREF = new Date(dateToCheck)
// If the parameter is a not a valid date, return false
if(DATEREF instanceof Date && isNaN(DATEREF)){
console.log("invalid date format")
return false}
// Get separated date infos (the date of today, the current month and the current year) based on the date given as parameter
const [dayR, monthR, yearR] = [DATEREF.getDate(), DATEREF.getMonth(), DATEREF.getFullYear()]
// get Monday date by substracting the day index (number) in the week from the day value (count)
//in the month (like october 15th - 5 (-> saturday index)) and +1 because
//JS weirdly starts the week on sundays
const monday = (WEEK.getDate() - WEEK.getDay()) + 1
// get Saturday date
const sunday = monday + 6
// Start verification
if (yearR !== WEEK.getFullYear()) { console.log("WRONG YEAR"); return false }
if (monthR !== WEEK.getMonth()) { console.log("WRONG MONTH"); return false }
if(dayR >= monday && dayR <= sunday) { return true }
else {console.log("WRONG DAY"); return false}
}
Try this
var gdate='01-05-2014';
date =Date.parse(gdate.split('-')[1]+'-'+gdate.split('-')[0]+'-'+gdate.split('-')[2]);
if(parseInt(date) < parseInt(Date.now()))
{
alert('small');
}else{
alert('big');
}
Fiddle
This question is very generic, hence people who are using date libraries also check for the answer, but I couldn't find any answer for the date libraries, hence I am posting the answer for Luxon users.
const fromDate = '2022-06-01T00:00:00.000Z';
const toDate = '2022-06-30T23:59:59.999Z';
const inputDate = '2022-08-09T20:26:13.380Z';
if (
DateTime.fromISO(inputDate) >= DateTime.fromISO(fromDate) &&
DateTime.fromISO(inputDate) <= DateTime.fromISO(toDate)
) {
console.log('within range');
} else {
console.log('not in range');
}

How can I calculate the number of years between two dates?

I want to get the number of years between two dates. I can get the number of days between these two days, but if I divide it by 365 the result is incorrect because some years have 366 days.
This is my code to get date difference:
var birthday = value;//format 01/02/1900
var dateParts = birthday.split("/");
var checkindate = new Date(dateParts[2], dateParts[0] - 1, dateParts[1]);
var now = new Date();
var difference = now - checkindate;
var days = difference / (1000*60*60*24);
var thisyear = new Date().getFullYear();
var birthyear = dateParts[2];
var number_of_long_years = 0;
for(var y=birthyear; y <= thisyear; y++){
if( (y % 4 == 0 && y % 100 == 0) || y % 400 == 0 ) {
number_of_long_years++;
}
}
The day count works perfectly. I am trying to do add the additional days when it is a 366-day year, and I'm doing something like this:
var years = ((days)*(thisyear-birthyear))
/((number_of_long_years*366) + ((thisyear-birthyear-number_of_long_years)*365) );
I'm getting the year count. Is this correct, or is there a better way to do this?
Sleek foundation javascript function.
function calculateAge(birthday) { // birthday is a date
var ageDifMs = Date.now() - birthday;
var ageDate = new Date(ageDifMs); // miliseconds from epoch
return Math.abs(ageDate.getUTCFullYear() - 1970);
}
Probably not the answer you're looking for, but at 2.6kb, I would not try to reinvent the wheel and I'd use something like moment.js. Does not have any dependencies.
The diff method is probably what you want: http://momentjs.com/docs/#/displaying/difference/
Using pure javascript Date(), we can calculate the numbers of years like below
document.getElementById('getYearsBtn').addEventListener('click', function () {
var enteredDate = document.getElementById('sampleDate').value;
// Below one is the single line logic to calculate the no. of years...
var years = new Date(new Date() - new Date(enteredDate)).getFullYear() - 1970;
console.log(years);
});
<input type="text" id="sampleDate" value="1980/01/01">
<div>Format: yyyy-mm-dd or yyyy/mm/dd</div><br>
<button id="getYearsBtn">Calculate Years</button>
No for-each loop, no extra jQuery plugin needed... Just call the below function.. Got from Difference between two dates in years
function dateDiffInYears(dateold, datenew) {
var ynew = datenew.getFullYear();
var mnew = datenew.getMonth();
var dnew = datenew.getDate();
var yold = dateold.getFullYear();
var mold = dateold.getMonth();
var dold = dateold.getDate();
var diff = ynew - yold;
if (mold > mnew) diff--;
else {
if (mold == mnew) {
if (dold > dnew) diff--;
}
}
return diff;
}
I use the following for age calculation.
I named it gregorianAge() because this calculation gives exactly how we denote age using Gregorian calendar. i.e. Not counting the end year if month and day is before the month and day of the birth year.
/**
* Calculates human age in years given a birth day. Optionally ageAtDate
* can be provided to calculate age at a specific date
*
* #param string|Date Object birthDate
* #param string|Date Object ageAtDate optional
* #returns integer Age between birthday and a given date or today
*/
gregorianAge = function(birthDate, ageAtDate) {
// convert birthDate to date object if already not
if (Object.prototype.toString.call(birthDate) !== '[object Date]')
birthDate = new Date(birthDate);
// use today's date if ageAtDate is not provided
if (typeof ageAtDate == "undefined")
ageAtDate = new Date();
// convert ageAtDate to date object if already not
else if (Object.prototype.toString.call(ageAtDate) !== '[object Date]')
ageAtDate = new Date(ageAtDate);
// if conversion to date object fails return null
if (ageAtDate == null || birthDate == null)
return null;
var _m = ageAtDate.getMonth() - birthDate.getMonth();
// answer: ageAt year minus birth year less one (1) if month and day of
// ageAt year is before month and day of birth year
return (ageAtDate.getFullYear()) - birthDate.getFullYear()
- ((_m < 0 || (_m === 0 && ageAtDate.getDate() < birthDate.getDate()))?1:0)
}
<input type="text" id="birthDate" value="12 February 1982">
<div style="font-size: small; color: grey">Enter a date in an acceptable format e.g. 10 Dec 2001</div><br>
<button onClick='js:alert(gregorianAge(document.getElementById("birthDate").value))'>What's my age?</button>
Little out of date but here is a function you can use!
function calculateAge(birthMonth, birthDay, birthYear) {
var currentDate = new Date();
var currentYear = currentDate.getFullYear();
var currentMonth = currentDate.getMonth();
var currentDay = currentDate.getDate();
var calculatedAge = currentYear - birthYear;
if (currentMonth < birthMonth - 1) {
calculatedAge--;
}
if (birthMonth - 1 == currentMonth && currentDay < birthDay) {
calculatedAge--;
}
return calculatedAge;
}
var age = calculateAge(12, 8, 1993);
alert(age);
You can get the exact age using timesstamp:
const getAge = (dateOfBirth, dateToCalculate = new Date()) => {
const dob = new Date(dateOfBirth).getTime();
const dateToCompare = new Date(dateToCalculate).getTime();
const age = (dateToCompare - dob) / (365 * 24 * 60 * 60 * 1000);
return Math.floor(age);
};
let currentTime = new Date().getTime();
let birthDateTime= new Date(birthDate).getTime();
let difference = (currentTime - birthDateTime)
var ageInYears=difference/(1000*60*60*24*365)
Yep, moment.js is pretty good for this:
var moment = require('moment');
var startDate = new Date();
var endDate = new Date();
endDate.setDate(endDate.getFullYear() + 5); // Add 5 years to second date
console.log(moment.duration(endDate - startDate).years()); // This should returns 5
getYears(date1, date2) {
let years = new Date(date1).getFullYear() - new Date(date2).getFullYear();
let month = new Date(date1).getMonth() - new Date(date2).getMonth();
let dateDiff = new Date(date1).getDay() - new Date(date2).getDay();
if (dateDiff < 0) {
month -= 1;
}
if (month < 0) {
years -= 1;
}
return years;
}
for(var y=birthyear; y <= thisyear; y++){
if( (y % 4 == 0 && y % 100 == 0) || y % 400 == 0 ) {
days = days-366;
number_of_long_years++;
} else {
days=days-365;
}
year++;
}
can you try this way??
function getYearDiff(startDate, endDate) {
let yearDiff = endDate.getFullYear() - startDate.getFullYear();
if (startDate.getMonth() > endDate.getMonth()) {
yearDiff--;
} else if (startDate.getMonth() === endDate.getMonth()) {
if (startDate.getDate() > endDate.getDate()) {
yearDiff--;
} else if (startDate.getDate() === endDate.getDate()) {
if (startDate.getHours() > endDate.getHours()) {
yearDiff--;
} else if (startDate.getHours() === endDate.getHours()) {
if (startDate.getMinutes() > endDate.getMinutes()) {
yearDiff--;
}
}
}
}
return yearDiff;
}
alert(getYearDiff(firstDate, secondDate));
getAge(month, day, year) {
let yearNow = new Date().getFullYear();
let monthNow = new Date().getMonth() + 1;
let dayNow = new Date().getDate();
if (monthNow === month && dayNow < day || monthNow < month) {
return yearNow - year - 1;
} else {
return yearNow - year;
}
}
If you are using moment
/**
* Convert date of birth into age
* param {string} dateOfBirth - date of birth
* param {string} dateToCalculate - date to compare
* returns {number} - age
*/
function getAge(dateOfBirth, dateToCalculate) {
const dob = moment(dateOfBirth);
return moment(dateToCalculate).diff(dob, 'years');
};
If you want to calculate the years and keep the remainder of the time left for further calculations you can use this function most of the other answers discard the remaining time.
It returns the years and the remainder in milliseconds. This is useful if you want to calculate the time (days or minutes) left after you calculate the years.
The function works by first calculating the difference in years directly using *date.getFullYear()*.
Then it checks if the last year between the two dates is up to a full year by setting the two dates to the same year.
Eg:
oldDate= 1 July 2020,
newDate= 1 June 2022,
years =2020 -2022 =2
Now set old date to new date's year 2022
oldDate = 1 July, 2022
If the last year is not up to a full year then the year is subtracted by 1, the old date is set to the previous year and the interval from the previous year to the current date is calculated to give the remainder in milliseconds.
In the example since old date July 2022 is greater than June 2022 then it means a full year has not yet elapsed (from July 2021 to June 2022) therefore the year count is greater by 1. So years should be decreased by 1. And the actual year count from July 2020 to June 2022 is 1 year ,... months.
If the last year is a full year then the year count by *date.getFullYear()* is correct and the time that has elapsed from the current old date to new date is calculated as the remainder.
If old date= 1 April, 2020, new date = 1 June, 2022 and old date is set to April 2022 after calculating the year =2.
Eg: from April 2020 to June 2022 a duration of 2 years has passed with the remainder being the time from April 2022 to June 2022.
There are also checks for cases where the two dates are in the same year and if the user enters the dates in the wrong order the new Date is less recent than the old Date.
let getYearsAndRemainder = (newDate, oldDate) => {
let remainder = 0;
// get initial years between dates
let years = newDate.getFullYear() - oldDate.getFullYear();
if (years < 0) {// check to make sure the oldDate is the older of the two dates
console.warn('new date is lesser than old date in year difference')
years = 0;
} else {
// set the old date to the same year as new date
oldDate.setFullYear(newDate.getFullYear());
// check if the old date is less than new date in the same year
if (oldDate - newDate > 0) {
//if true, the old date is greater than the new date
// the last but one year between the two dates is not up to a year
if (years != 0) {// dates given in inputs are in the same year, no need to calculate years if the number of years is 0
console.log('Subtracting year');
//set the old year to the previous year
years--;
oldDate.setFullYear(oldDate.getFullYear() - 1);
}
}
}
//calculate the time difference between the old year and newDate.
remainder = newDate - oldDate;
if (remainder < 0) { //check for negative dates due to wrong inputs
console.warn('old date is greater than new Date');
console.log('new date', newDate, 'old date', oldDate);
}
return { years, remainder };
}
let old = new Date('2020-07-01');
console.log( getYearsAndRemainder(new Date(), old));
Date calculation work via the Julian day number. You have to take the first of January of the two years. Then you convert the Gregorian dates into Julian day numbers and after that you take just the difference.
Maybe my function can explain better how to do this in a simple way without loop, calculations and/or libs
function checkYearsDifference(birthDayDate){
var todayDate = new Date();
var thisMonth = todayDate.getMonth();
var thisYear = todayDate.getFullYear();
var thisDay = todayDate.getDate();
var monthBirthday = birthDayDate.getMonth();
var yearBirthday = birthDayDate.getFullYear();
var dayBirthday = birthDayDate.getDate();
//first just make the difference between years
var yearDifference = thisYear - yearBirthday;
//then check months
if (thisMonth == monthBirthday){
//if months are the same then check days
if (thisDay<dayBirthday){
//if today day is before birthday day
//then I have to remove 1 year
//(no birthday yet)
yearDifference = yearDifference -1;
}
//if not no action because year difference is ok
}
else {
if (thisMonth < monthBirthday) {
//if actual month is before birthday one
//then I have to remove 1 year
yearDifference = yearDifference -1;
}
//if not no action because year difference is ok
}
return yearDifference;
}
Bro, moment.js is awesome for this:
The diff method is what you want: http://momentjs.com/docs/#/displaying/difference/
The below function return array of years from the year to the current year.
const getYears = (from = 2017) => {
const diff = moment(new Date()).diff(new Date(`01/01/${from}`), 'years') ;
return [...Array(diff >= 0 ? diff + 1 : 0).keys()].map((num) => {
return from + num;
});
}
console.log(getYears(2016));
<script src="https://momentjs.com/downloads/moment.js"></script>
function dateDiffYearsOnly( dateNew,dateOld) {
function date2ymd(d){ w=new Date(d);return [w.getFullYear(),w.getMonth(),w.getDate()]}
function ymd2N(y){return (((y[0]<<4)+y[1])<<5)+y[2]} // or 60 and 60 // or 13 and 32 // or 25 and 40 //// with ...
function date2N(d){ return ymd2N(date2ymd(d))}
return (date2N(dateNew)-date2N(dateOld))>>9
}
test:
dateDiffYearsOnly(Date.now(),new Date(Date.now()-7*366*24*3600*1000));
dateDiffYearsOnly(Date.now(),new Date(Date.now()-7*365*24*3600*1000))
I went for the following very simple solution. It does not assume you were born in 1970 and it also takes into account the hour of the given birthday date.
function age(birthday) {
let now = new Date();
let year = now.getFullYear();
let years = year - birthday.getFullYear();
birthday = new Date(birthday.getTime()); // clone
birthday.setFullYear(year);
return now >= birthday ? years : years - 1;
}
This one Help you...
$("[id$=btnSubmit]").click(function () {
debugger
var SDate = $("[id$=txtStartDate]").val().split('-');
var Smonth = SDate[0];
var Sday = SDate[1];
var Syear = SDate[2];
// alert(Syear); alert(Sday); alert(Smonth);
var EDate = $("[id$=txtEndDate]").val().split('-');
var Emonth = EDate[0];
var Eday = EDate[1];
var Eyear = EDate[2];
var y = parseInt(Eyear) - parseInt(Syear);
var m, d;
if ((parseInt(Emonth) - parseInt(Smonth)) > 0) {
m = parseInt(Emonth) - parseInt(Smonth);
}
else {
m = parseInt(Emonth) + 12 - parseInt(Smonth);
y = y - 1;
}
if ((parseInt(Eday) - parseInt(Sday)) > 0) {
d = parseInt(Eday) - parseInt(Sday);
}
else {
d = parseInt(Eday) + 30 - parseInt(Sday);
m = m - 1;
}
// alert(y + " " + m + " " + d);
$("[id$=lblAge]").text("your age is " + y + "years " + m + "month " + d + "days");
return false;
});
if someone needs for interest calculation year in float format
function floatYearDiff(olddate, newdate) {
var new_y = newdate.getFullYear();
var old_y = olddate.getFullYear();
var diff_y = new_y - old_y;
var start_year = new Date(olddate);
var end_year = new Date(olddate);
start_year.setFullYear(new_y);
end_year.setFullYear(new_y+1);
if (start_year > newdate) {
start_year.setFullYear(new_y-1);
end_year.setFullYear(new_y);
diff_y--;
}
var diff = diff_y + (newdate - start_year)/(end_year - start_year);
return diff;
}

Categories

Resources