Working Days Javascript with Extra Dates - javascript

I have a function which calculates a date that is passed and adds a given number of days to the result ensuring the outputted date doesn't fall on a weekend.
The function
function addWorkingDays(datStartDate, lngNumberOfWorkingDays, blnIncSat, blnIncSun) {
var intWorkingDays = 5;
var intNonWorkingDays = 2;
var intStartDay = datStartDate.getDay(); // 0=Sunday ... 6=Saturday
var intOffset;
var intModifier = 0;
if (blnIncSat) { intWorkingDays++; intNonWorkingDays--; }
if (blnIncSun) { intWorkingDays++; intNonWorkingDays--; }
var newDate = new Date(datStartDate)
if (lngNumberOfWorkingDays >= 0) {
// Moving Forward
if (!blnIncSat && blnIncSun) {
intOffset = intStartDay;
} else {
intOffset = intStartDay - 1;
}
// Special start Saturday rule for 5 day week
if (intStartDay == 6 && !blnIncSat && !blnIncSun) {
intOffset -= 6;
intModifier = 1;
}
} else {
// Moving Backward
if (blnIncSat && !blnIncSun) {
intOffset = intStartDay - 6;
} else {
intOffset = intStartDay - 5;
}
// Special start Sunday rule for 5 day week
if (intStartDay === 0 && !blnIncSat && !blnIncSun) {
intOffset++;
intModifier = 1;
}
}
// ~~ is used to achieve integer division for both positive and negative numbers
newDate.setDate(datStartDate.getDate() + new Number((~~((lngNumberOfWorkingDays + intOffset) / intWorkingDays) * intNonWorkingDays) + lngNumberOfWorkingDays + intModifier));
return newDate;
}
I need to now add some dates to this function for it to take into account, these are public holiday's in Sydney Australia. What I am looking to achieve is the following.
var newDate = addWorkingDays('30/09/2015', 3, false, false);
In this example the returned date would fall on the 03/10/2015 which is a public holiday and therefore we would need to return the 04/10/2015
The dates in question are:
01/01/2015 New Year's Day
26/01/2015 Australia Day
09/03/2015 Labour Day / Eight Hours Day / Adelaide Cup / Canberra Day
03/04/2015 Good Friday
06/04/2015 Easter Monday
25/04/2015 ANZAC Day
08/06/2015 Queen's Birthday
03/08/2015 Bank Holiday / Picnic Day
05/10/2015 Labour Day
03/11/2015 Melbourne Cup
25/12/2015 Christmas Day
26/12/2015 Boxing Day
Given the function above can someone help me to amend the function to take these dates into account.

As it is your code gives me errors when I try to call it like you specify, but regardless you should simply be able to check if the date you're going to give as an answer is one of your invalid dates, and if so then return the next working day:
(pseudocode)
newDate.setDate(datStartDate.getDate() + new Number((~~((lngNumberOfWorkingDays + intOffset) / intWorkingDays) * intNonWorkingDays) + lngNumberOfWorkingDays + intModifier));
if (newDate == "01/01/2015" || newDate == "26/01/2015" || ....) {
return addWorkingDays(newDate, 1, blnIncSat, blnIncSun);
}
else {
return newDate;
}

Related

Check if weekend exist in date range using javascript

Wondering if anyone has a solution for checking if a weekend exist between two dates and its range.
var date1 = 'Apr 10, 2014';
var date2 = 'Apr 14, 2014';
funck isWeekend(date1,date2){
//do function
return isWeekend;
}
Thank you in advance.
EDIT Adding what I've got so far. Check the two days.
function isWeekend(date1,date2){
//do function
if(date1.getDay() == 6 || date1.getDay() == 0){
return isWeekend;
console.log("weekend")
}
if(date2.getDay() == 6 || date2.getDay() == 0){
return isWeekend;
console.log("weekend")
}
}
Easiest would be to just iterate over the dates and return if any of the days are 6 (Saturday) or 0 (Sunday)
Demo: http://jsfiddle.net/abhitalks/xtD5V/1/
Code:
function isWeekend(date1, date2) {
var d1 = new Date(date1),
d2 = new Date(date2),
isWeekend = false;
while (d1 < d2) {
var day = d1.getDay();
isWeekend = (day === 6) || (day === 0);
if (isWeekend) { return true; } // return immediately if weekend found
d1.setDate(d1.getDate() + 1);
}
return false;
}
If you want to check if the whole weekend exists between the two dates, then change the code slightly:
Demo 2: http://jsfiddle.net/abhitalks/xtD5V/2/
Code:
function isFullWeekend(date1, date2) {
var d1 = new Date(date1),
d2 = new Date(date2);
while (d1 < d2) {
var day = d1.getDay();
if ((day === 6) || (day === 0)) {
var nextDate = d1; // if one weekend is found, check the next date
nextDate.setDate(d1.getDate() + 1); // set the next date
var nextDay = nextDate.getDay(); // get the next day
if ((nextDay === 6) || (nextDay === 0)) {
return true; // if next day is also a weekend, return true
}
}
d1.setDate(d1.getDate() + 1);
}
return false;
}
You are only checking if the first or second date is a weekend day.
Loop from the first to the second date, returning true only if one of the days in between falls on a weekend-day:
function isWeekend(date1,date2){
var date1 = new Date(date1), date2 = new Date(date2);
//Your second code snippet implies that you are passing date objects
//to the function, which differs from the first. If it's the second,
//just miss out creating new date objects.
while(date1 < date2){
var dayNo = date1.getDay();
date1.setDate(date1.getDate()+1)
if(!dayNo || dayNo == 6){
return true;
}
}
}
JSFiddle
Here's what I'd suggest to test if a weekend day falls within the range of two dates (which I think is what you were asking):
function containsWeekend(d1, d2)
{
// note: I'm assuming d2 is later than d1 and that both d1 and d2 are actually dates
// you might want to add code to check those conditions
var interval = (d2 - d1) / (1000 * 60 * 60 * 24); // convert to days
if (interval > 5) {
return true; // must contain a weekend day
}
var day1 = d1.getDay();
var day2 = d2.getDay();
return !(day1 > 0 && day2 < 6 && day2 > day1);
}
fiddle
If you need to check if a whole weekend exists within the range, then it's only slightly more complicated.
It doesn't really make sense to pass in two dates, especially when they are 4 days apart. Here is one that only uses one day which makes much more sense IMHO:
var date1 = 'Apr 10, 2014';
function isWeekend(date1){
var aDate1 = new Date(date1);
var dayOfWeek = aDate1.getDay();
return ((dayOfWeek == 0) || (dayOfWeek == 6));
}
I guess this is the one what #MattBurland sugested for doing it without a loop
function isWeekend(start,end){
start = new Date(start);
if (start.getDay() == 0 || start.getDay() == 6) return true;
end = new Date(end);
var day_diff = (end - start) / (1000 * 60 * 60 * 24);
var end_day = start.getDay() + day_diff;
if (end_day > 5) return true;
return false;
}
FIDDLE
Whithout loops, considering "sunday" first day of week (0):
Check the first date day of week, if is weekend day return true.
SUM "day of the week" of the first day of the range and the number of days in the lap.
If sum>5 return true
Use Date.getDay() to tell if it is a weekend.
if(tempDate.getDay()==6 || tempDate.getDay()==0)
Check this working sample:
http://jsfiddle.net/danyu/EKP6H/2/
This will list out all weekends in date span.
Modify it to adapt to requirements.
Good luck.

Moment.js how to get week of month? (google calendar style)

I am using Moment.js and it is great. The problem I have now is that I can't figure out how to get the week of the month a certain date is. I can only find "week of year" in the Moment js docs. For example, if I choose today's date (2/12/2014), I would like to know that this date is in the second week of this month of february and consequently, it is the second wednesday of the month. Any ideas?
EDIT:
I guess some clarification is necessary. What I need most is the nth number of a certain day in a month. For example, (from the comments) Feb 1, 2014 would be the first Saturday of the month. Feb 3, 2014 would be the first Monday of the month even though it is "technically" the second week of the month. Basically, exactly how google calendar's repeat function classifies days.
It seems that moment.js does not have the method that implements the functionality that you are looking for.
However, you can find the nth number of a certain day of the week in a month is using the Math.ceil of the date / 7
For example:
var firstFeb2014 = moment("2014-02-01"); //saturday
var day = firstFeb2014.day(); //6 = saturday
var nthOfMoth = Math.ceil(firstFeb2014.date() / 7); //1
var eightFeb2014 = moment("2014-02-08"); //saturday, the next one
console.log( Math.ceil(eightFeb2014.date() / 7) ); //prints 2, as expected
It looks like this is the number you are looking for, as demonstrated by the following test
function test(mJsDate){
var str = mJsDate.toLocaleString().substring(0, 3) +
" number " + Math.ceil(mJsDate.date() / 7) +
" of the month";
return str;
}
for(var i = 1; i <= 31; i++) {
var dayStr = "2014-01-"+ i;
console.log(dayStr + " " + test(moment(dayStr)) );
}
//examples from the console:
//2014-01-8 Wed number 2 of the month
//2014-01-13 Mon number 2 of the month
//2014-01-20 Mon number 3 of the month
//2014-01-27 Mon number 4 of the month
//2014-01-29 Wed number 5 of the month
When calculating the week of the month based on a given date, you have to take the offset into account. Not all months start on the first day of the week.
If you want to take this offset into account, you can use something something like the following if you are using moment.
function weekOfMonth (input = moment()) {
const firstDayOfMonth = input.clone().startOf('month');
const firstDayOfWeek = firstDayOfMonth.clone().startOf('week');
const offset = firstDayOfMonth.diff(firstDayOfWeek, 'days');
return Math.ceil((input.date() + offset) / 7);
}
Simple using moment.js
function week_of_month(date) {
prefixes = [1,2,3,4,5];
return prefixes[0 | moment(date).date() / 7]
}
This library adds the function moment.weekMonth()
https://github.com/c-trimm/moment-recur
I made some modifications based on feedback.
let weeks = moment().weeks() - moment().startOf('month').weeks() + 1;
weeks = (weeks + 52) % 52;
On days passing through the next year, the week value will be negative so I had to add 52.
What about something like:
weekOfCurrentMonth = (moment().week() - (moment().month()*4));
This takes the current week of the year, and subtracts it by the 4 times the number of previous months. Which should give you the week of the current month
I think the answer to this question will be helpful, even though it doesn't use moment.js as requested:
Get week of the month
function countWeekdayOccurrencesInMonth(date) {
var m = moment(date),
weekDay = m.day(),
yearDay = m.dayOfYear(),
count = 0;
m.startOf('month');
while (m.dayOfYear() <= yearDay) {
if (m.day() == weekDay) {
count++;
}
m.add('days', 1);
}
return count;
}
There is a problem with #Daniel Earwicker answer.
I was using his function in my application and the while loop was infinite because of the following situation:
I was trying to figure out which week of december (2016) was the day 31.
the first day of december was day 336 of the year. The last day of december was day 366 of the year.
Problem here: When it was day 366 (31 of december, last day of the year) the code added another day to this date. But with another day added it would be day 1 of january of 2017. Therefore the loop never ended.
while (m.dayOfYear() <= yearDay) {
if (m.day() == weekDay) {
count++;
}
m.add('days', 1);
}
I added the following lines to the code so the problem would be fixed:
function countWeekdayOccurrencesInMonth(date) {
var m = moment(date),
weekDay = m.day(),
yearDay = m.dayOfYear(),
year = m.year(),
count = 0;
m.startOf('month');
while (m.dayOfYear() <= yearDay && m.year() == year) {
if (m.day() == weekDay) {
count++;
}
m.add('days', 1);
}
return count;
}
It verifies if it is still in the same year of the date being veryfied
Here's Robin Malfait's solution implemented with the lightweight library date-fns
import {
differenceInDays,
startOfMonth,
startOfWeek,
getDate
} from 'date-fns'
const weekOfMonth = function (date) {
const firstDayOfMonth = startOfMonth(date)
const firstDayOfWeek = startOfWeek(firstDayOfMonth)
const offset = differenceInDays(firstDayOfMonth, firstDayOfWeek)
return Math.ceil((getDate(date) + offset) / 7)
}
export default weekOfMonth
I'd do the following:
let todaysDate = moment(moment.now());
let endOfLastMonth = moment(get(this, 'todaysDate')).startOf('month').subtract(1, 'week');
let weekOfMonth = todaysDate.diff(endOfLastMonth, 'weeks');
That gets todaysDate and the endOfLastMonth and then uses Moment's built-in diff() method to compute the current month's week number.
It's not built-in, but basically you can subtract the week number of the start of the month from the week number of the date in question.
function weekOfMonth(m) {
return m.week() - moment(m).startOf('month').week() + 1;
}
Credit goes to code by original author, give him a star if it helped you.
How about this?
const moment = require("moment");
// Generate Week Number of The Month From Moment Date
function getWeekOfMonth(input = moment()) {
let dayOfInput = input.clone().day(); // Saunday is 0 and Saturday is 6
let diffToNextWeek = 7 - dayOfInput;
let nextWeekStartDate = input.date() + diffToNextWeek;
return Math.ceil((nextWeekStartDate) / 7);
}
Simple code, but has been working for me.
const weekOfTheMonth = (myMomentDate) => {
const startDay = moment(myMomentDate).startOf('week');
const day = parseInt(startDay.format('DD'),10);
if(day > 28){
return 5;
}
if((day > 21) && (day <= 28) ){
return 4;
}
if((day > 14) && (day <= 21) ){
return 3;
}
if((day > 7) && (day <= 14) ){
return 2;
}
return 1;
}

Calculate an expected delivery date (accounting for holidays) in business days using JavaScript?

After revisiting this script, and some modifications, the following is available to allow a user to add a feature that calculates the expected delivery date.
// array of ISO YYYY-MM-DD format dates
publicHolidays = {
uk:["2020-01-01","2020-04-10","2020-04-13","2020-05-08","2020-05-25",
"2020-08-03","2020-08-31","2020-12-25","2020-12-28"],
usa:["2020-01-01","2020-01-20","2020-02-14","2020-02-17","2020-04-10",
"2020-04-12","2020-05-10","2020-05-25","2020-06-21","2020-07-03",
"2020-07-04","2020-09-07","2020-10-12","2020-10-31","2020,11,11",
"2020-11-26","2020-12-25"]
}
// check if there is a match in the array
Date.prototype.isPublicHoliday = function( data ){// we check for a public holiday
if(!data) return 1;
return data.indexOf(this.toISOString().slice(0,10))>-1? 0:1;
}
// calculation of business days
Date.prototype.businessDays = function( d, holidays ){
var holidays = holidays || false, t = new Date( this ); // copy date.
while( d ){ // we loop while d is not zero...
t.setDate( t.getDate() + 1 ); // set a date and test it
switch( t.getDay() ){ // switch is used to allow easier addition of other days of the week
case 0: case 6: break;// sunday & saturday
default: // check if we are a public holiday or not
d -= t.isPublicHoliday( holidays );
}
}
return t.toISOString().slice(0,10); // just the YYY-MM-DD
}
// dummy var, could be a form field input
OrderDate = "2020-02-12";
// test with a UK holiday date
var deliveryDate = new Date(OrderDate).businessDays(7, publicHolidays.usa);
// expected output 2020-02-25
console.log("Order date: %s, Delivery date: %s",OrderDate,deliveryDate );
Order date: 2020-02-12, Delivery date: 2020-02-25
The prototype is written to allow inputs from forms (HTML5 forms) of date type inputs as they are already in an ISO YYYY-MM-DD format and the output is formatted as such should that be needing to update a particular field.
The typical use would be...
var delDate = new Date( ISOdate ).businessDays( addBusinessDays, holidayData );
where the delDate is an ISO format date, eg, 2020-01-01
I've adapted Mark Giblin's revised code to better deal with end of year dates and also U.S. federal holidays. See below...
function businessDaysFromDate(date,businessDays) {
var counter = 0, tmp = new Date(date);
while( businessDays>=0 ) {
tmp.setTime( date.getTime() + counter * 86400000 );
if(isBusinessDay (tmp)) {
--businessDays;
}
++counter;
}
return tmp;
}
function isBusinessDay (date) {
var dayOfWeek = date.getDay();
if(dayOfWeek === 0 || dayOfWeek === 6) {
// Weekend
return false;
}
holidays = [
'12/31+5', // New Year's Day on a saturday celebrated on previous friday
'1/1', // New Year's Day
'1/2+1', // New Year's Day on a sunday celebrated on next monday
'1-3/1', // Birthday of Martin Luther King, third Monday in January
'2-3/1', // Washington's Birthday, third Monday in February
'5~1/1', // Memorial Day, last Monday in May
'7/3+5', // Independence Day
'7/4', // Independence Day
'7/5+1', // Independence Day
'9-1/1', // Labor Day, first Monday in September
'10-2/1', // Columbus Day, second Monday in October
'11/10+5', // Veterans Day
'11/11', // Veterans Day
'11/12+1', // Veterans Day
'11-4/4', // Thanksgiving Day, fourth Thursday in November
'12/24+5', // Christmas Day
'12/25', // Christmas Day
'12/26+1', // Christmas Day
];
var dayOfMonth = date.getDate(),
month = date.getMonth() + 1,
monthDay = month + '/' + dayOfMonth;
if(holidays.indexOf(monthDay)>-1){
return false;
}
var monthDayDay = monthDay + '+' + dayOfWeek;
if(holidays.indexOf(monthDayDay)>-1){
return false;
}
var weekOfMonth = Math.floor((dayOfMonth - 1) / 7) + 1,
monthWeekDay = month + '-' + weekOfMonth + '/' + dayOfWeek;
if(holidays.indexOf(monthWeekDay)>-1){
return false;
}
var lastDayOfMonth = new Date(date);
lastDayOfMonth.setMonth(lastDayOfMonth.getMonth() + 1);
lastDayOfMonth.setDate(0);
var negWeekOfMonth = Math.floor((lastDayOfMonth.getDate() - dayOfMonth - 1) / 7) + 1,
monthNegWeekDay = month + '~' + negWeekOfMonth + '/' + dayOfWeek;
if(holidays.indexOf(monthNegWeekDay)>-1){
return false;
}
return true;
}
Thanks for your input guys, I had a long hard re-think over the approach I was making for this and came up with this little number...
var businessDays = 7, counter = 0; // set to 1 to count from next business day
while( businessDays>0 ){
var tmp = new Date();
var startDate = new Date();
tmp.setDate( startDate .getDate() + counter++ );
switch( tmp.getDay() ){
case 0: case 6: break;// sunday & saturday
default:
businessDays--;
};
}
The idea was to start with the business days and count backwards to zero for each day encountered that fell in to the range of a business day. This use of switch would enable a person to declare a day in the week as a non-business day, for example someone may not work on a monday, therefore the addition of case:1 would include a monday.
This is a simple script and does not take in to account public or bank holidays, that would be asking for a much more complex script to work with.
The result is a date that is set to the date of shipping, the user can then extract the date info in any format that they please, eg.
var shipDate = tmp.toUTCString().slice(1,15);
We have UI that defaults search inputs to last business day or a week-ago.
Here's something that works both forward and backward.
// add (or subtract) business days to provided date
addBusinessDays = function (startingDate, daysToAdjust) {
var newDate = new Date(startingDate.valueOf()),
businessDaysLeft,
isWeekend,
direction;
// Timezones are scary, let's work with whole-days only
if (daysToAdjust !== parseInt(daysToAdjust, 10)) {
throw new TypeError('addBusinessDays can only adjust by whole days');
}
// short-circuit no work; make direction assignment simpler
if (daysToAdjust === 0) {
return startingDate;
}
direction = daysToAdjust > 0 ? 1 : -1;
// Move the date in the correct direction
// but only count business days toward movement
businessDaysLeft = Math.abs(daysToAdjust);
while (businessDaysLeft) {
newDate.setDate(newDate.getDate() + direction);
isWeekend = newDate.getDay() in {0: 'Sunday', 6: 'Saturday'};
if (!isWeekend) {
businessDaysLeft--;
}
}
return newDate;
};
It would be easy to pass in an optional holidays data structure and adjust for that as well.
However, generating a holidays data structure, well, that will take a little more effort and is specific not only to every country and region, but also to every organization.
Your main problem was that adding safety each time meant you were adding multiple days each time it looped, instead of 1. So first loop = 1, second = 1+2, etc.
I believe this works as you'd like:
var businessDays = 10; // this will come from a form
var counter = 0; // I have a counter
var safety = 0; // I have a safety variable
var ship = today = new Date(); // I have the current date and an initialized shipping variable but the buy date will come from a form
console.log(">>> today = " + today);
// now the loop...
while( ++safety <30 ){
ship.setDate(ship.getDate()+1 );
switch( ship.getDay() ){
case 0: // Sunday
case 6: // Saturday
break;
default:
counter++;
}
if( counter >= businessDays ) break;
}
// add a number of days
// the expected shipping date
console.log(">>> days = " + businessDays);
console.log(">>> ship = " + ship);
Change line 7 from
ship.setDate( safety ); // add a number of days
to
ship.setDate( ship.getDate() + safety );
The problem was that you want to add days, not set days.
I needed something similar but a little different and this is what I came up with.
Holidays are added in an object with one key for each month that has holidays. That key then has an array of days in that month that are considered holidays.
function getDueDate(date) {
var numBusinessDays = 20;
var saturday = 6;
var sunday = 0;
var holidays = {
/* Months are zero-based. 0 = Jan, 11 = Dec */
0: [1, 2],
1: [6],
3: [24],
11: [25, 26]
};
var dayOfWeek = null;
var dayOfMonth = null;
var month = null;
var isWeekday = null;
var monthHolidays = null;
var isHoliday = null;
while (numBusinessDays > 0) {
dayOfWeek = date.getDay();
dayOfMonth = date.getDate();
month = date.getMonth();
isWeekday = dayOfWeek !== saturday && dayOfWeek !== sunday;
monthHolidays = holidays[month];
isHoliday = monthHolidays
? monthHolidays.indexOf(dayOfMonth) > -1
: false;
if (isWeekday && !isHoliday) --numBusinessDays;
date.setDate(dayOfMonth + 1);
}
return date;
}
ship.setDate( safety ); // add a number of days
Doesn't add days. It sets the day.
More info
The setDate() method sets the day of the Date object relative to the beginning of the currently set month.
If you want to add days do something like this:
ship.setDate(ship.getDate()+1);
I just found this script which is working nice, you can give an optional array for your country's holidays
function addBusinessDays(date, days, holidays) {
var calendar = java.util.Calendar.getInstance();
calendar.setTimeInMillis(date.getTime());
var numberOfDaysToAdd = Math.abs(days);
var daysToAdd = days < 0 ? -1 : 1;
var businessDaysAdded = 0;
function isHoliday(dateToCheck) {
if (holidays && holidays.length > 0) {
for (var i = 0; i < holidays.length; i++) {
if (holidays[i].getFullYear() == dateToCheck.get(java.util.Calendar.YEAR) && holidays[i].getMonth() == dateToCheck.get(java.util.Calendar.MONTH) && holidays[i].getDate() == dateToCheck.get(java.util.Calendar.DAY_OF_MONTH)) {
return true;
}
}
}
return false;
}
while (businessDaysAdded < numberOfDaysToAdd) {
calendar.add(java.util.Calendar.DATE, daysToAdd);
if (calendar.get(java.util.Calendar.DAY_OF_WEEK) == java.util.Calendar.SATURDAY || calendar.get(java.util.Calendar.DAY_OF_WEEK) == java.util.Calendar.SUNDAY) {
// add another day
continue;
}
if (isHoliday(calendar)) {
// add another day
continue;
}
businessDaysAdded ++;
}
return new Date(calendar.getTimeInMillis());
}

Javascript: calculating remaining time (and then rent) on a tenancy (Rent Calculator)

I work at a corporate estate agency and I'm creating an internal page for staff use that will contain just a few small tools for them to use among other things.
One of the things I've been trying to put together is a Rent Calculator, which, given a rental amount and a lease expiry date from the user, needs to determine the time left (from today) on the lease and then advise how much rent is left to pay on that lease.
I've got it working, mostly, but as you can see it's fairly long (I'm assuming to some extent it has to be) and I feel reasonably messy:
//calculates the remaining rent left to pay for terminated leases
$("input[name='calcRent']").click(function() {
//gets rent and daily rent for later calculations
var rent = $("input[name='rentRent']").val();
var dailyRate = (rent * 12) / 365;
var leaseExpiry = $("input[name='leaseExpiry']").val();
var remRent = $("input[name='remRent']");
//breaks down lease expiry date and today's date into day, month, year parts
//so that units can be used in calculations
var ldd = leaseExpiry.substr(0,2);
ldd = parseInt(ldd, 10);
var lmm = leaseExpiry.substr(3,2);
lmm = parseInt(lmm, 10);
var lyyyy = leaseExpiry.substr(6,4);
lyyyy = parseInt(lyyyy, 10);
var date = new Date();
var tdd = date.getDate();
var tmm = date.getMonth()+1;
var tyyyy = date.getFullYear();
//if the expiry month is next year (or later) add 12 to expiry
//month value to make "lmm - tmm" calculation give positive value
if (lyyyy > tyyyy) {
lmm += (12 * (lyyyy - tyyyy));
}
//takes the current month from the expiry month to get the number of
//whole months left in the lease, then checks day values to see whether
//we have already passed the rent due date for this month (and so there's
//one less whole month left than we originally thought), taking 1 from
//wholeMths value if so
var wholeMths = lmm - tmm;
if (ldd == (tdd - 1)) {
wholeMths = wholeMths;
} else if (ldd < (tdd - 1)) {
wholeMths -= 1;
}
//works out if there are any days to be charged at daily rate (i.e. not
//part of a whole month). If today's date(tdd) == expiry date(ldd)+1 we have no
//leftover days (rental month runs like so: 12/04 - 11/05). If tdd > ldd+1
//(leftover days cross over a month end) we set checkMonth to true so the following
//if statement runs
var checkMonth = false;
var daysLeft = 0;
if (tdd == (ldd + 1)) {
daysLeft = 0;
} else if (tdd > ldd + 1) {
daysLeft = (31 - tdd) + ldd;
checkMonth = true;
} else {
daysLeft = ldd - tdd;
}
//as per the above line: "daysLeft = (31 - tdd) + ldd;" we assume months have 31 days
//as the majority do, this if checks whether the month end that we cross over with our
//leftover days actually has 30 days, if not we check whether it's February and whether
//it's a leap year so that we get the appropriate no. of days to charge for - if it meets
//any of these criteria the relevant no. of days are subtracted from daysLeft
if ((lmm == 05 || lmm == 07 || lmm == 10 || lmm == 12
|| lmm == 17 || lmm == 19 || lmm == 22 || lmm == 24) && checkMonth) {
daysLeft -= 1;
} else if ((lmm == 03 || lmm == 15) && checkMonth) {
if (lyyyy % 4 == 0) {
daysLeft -= 2;
} else {
daysLeft -= 3;
}
}
checkMonth = false;
var balance = (wholeMths * rent) + (daysLeft * dailyRate);
remRent.val(balance.toFixed(2));
});
One of the bits that's especially bugging me is where the lease expiry occurs in a subsequent year. I haven't got my head round how to tidily deal with the 'value' of that month (as you can see in the final if).
Any suggestions on this would be appreciated as the number and volume of the comments seem a bit disproportionate to the actual code - but I think they're necessary at the moment as it's not too clear what's going on.
Thanks,
Good work on what you have done, but you need to take advantage of the built-in date calculations available in JavaScript using the Date class.
Specifically to get the number of days between to dates you can use the following logic:
var currentDate = new Date(); // This will get today's date
currentDate.setHours(0,0,0,0); // Remove time from consideration
// As recommended by #NickSlash
// The following get's the lease expiration date using the year,
// month and date that you have already extracted from the input
var leaseExpirationDate = new Date( lyyyy, lmm, ldd );
// The number of days remaining in the lease is simply the following:
var one_day = 1000*60*60*24;
var daysLeftInLease = (leaseExpirationDate - currentDate ) / one_day;
This magic happens because internally the Date class keeps the date value as the number milliseconds since 1/1/1970. Therefore if you subtract two Date objects you get the number of milliseconds between them. You can then simply divide that value by the number of milliseconds in one day to get the number of days between the dates.

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