functions(partial functions) in javascript - javascript

write a function(not a generator) called displayDayNumber(dateString) that satisfies the following rule.
var dayNumber =displayDayNumber("Nov 5,2017"); //309
console.log(dayNumber ()); // 310
dayNumber("Oct 31 2017")); //304
dayNumber();//305
So far My code is working for one time dateString pass value but it is not calculating based when I am passing new value in dayNumber.
var dayNumber =function(dateString=new Date().toDateString())
{
var currentString=dateString;
var no=dateString.substring(8,10);
// console.log(no);
return function () {
// console.log("dateString=",dateString);
var b = calculateNumber(dateString) //helper function to calculate day No
{
var no = dateString.substring(8, 10);
var toNo = parseInt(no) + 1;
var thenString = toNo.toString() + ' ';
var replacecharacter = dateString.replace(no, thenString);
dateString = replacecharacter;
return b;
};
return dateString;
};
}
let genDayNumber=dayNumber ("Sat Nov 05 2017"); //309 //working
genDayNumber(); //working
genDayNumber("Wed Oct 31 2017")); //304 not working
genDayNumber(); //not working

The function you're returning doesn't take an argument, so when you're passing in "Wed Oct 31 2017", it's simply ignored.
You need to modify the returned function to accept a value.
Here is a working example
var dayNumber =displayDayNumber("Nov 5,2017"); //309
console.log(dayNumber); // 309
console.log(dayNumber()); // 310
console.log(dayNumber("Oct 31 2017")); //304
console.log(dayNumber())//305
function displayDayNumber(str) {
let date = new Date(str);
let day = dayOfYear(date);
var result = function(str) {
if (str) {
day = displayDayNumber(str);
return day;
} else {
return ++day;
}
}
result.valueOf = result.toString = function() { return day; }
return result;
}
function dayOfYear(now) {
// Taken from https://stackoverflow.com/questions/8619879/javascript-calculate-the-day-of-the-year-1-366
var start = new Date(now.getFullYear(), 0, 0);
var diff = (now - start) + ((start.getTimezoneOffset() - now.getTimezoneOffset()) * 60 * 1000);
var oneDay = 1000 * 60 * 60 * 24;
var day = Math.floor(diff / oneDay);
return day;
}

const dayNumber = date => {
let days = new Date(date).getDay();
return arg => {
if(arg){
return days = new Date(arg).getDay();
}
return ++days;
};
};

Related

Use asterisk * instead of year in object with dates?

I have this code to calculate days between dates and skip holidays.
var gon = {};
gon["holiday"] = "2015-08-28,2015-09-25,2016-08-31,2016-08-07,2015-08-13,2016-08-29,2016-01-07,2015-10-31".split(",");
// 2 helper functions - moment.js is 35K minified so overkill in my opinion
function pad(num) { return ("0" + num).slice(-2); }
function formatDate(date) { var d = new Date(date), dArr = [d.getFullYear(), pad(d.getMonth() + 1), pad(d.getDate())];return dArr.join('-');}
function calculateDays(first,last) {
var aDay = 24 * 60 * 60 * 1000,
daysDiff = parseInt((last.getTime()-first.getTime())/aDay,10);
if (daysDiff>0) {
for (var i = first.getTime(), lst = last.getTime(); i <= lst; i += aDay) {
var d = new Date(i);
console.log(d.getDay());
if (d.getDay() == 6 || d.getDay() == 0 // weekend
|| gon.holiday.indexOf(formatDate(d)) != -1) {
daysDiff--;
}
}
}
return daysDiff;
}
How can I use asterisk * instead of year to cover all years. I don't want to do like this
gon["holiday"] = "2018-08-28,2018-09-25,2019-08-28,2019-09-25,2020-08-28,2020-09-25,2021-08-28,2021-09-25".split(",");
Can I do something like this
gon["holiday"] = "*-08-28,*-09-25".split(",");
This code could do the work for you:
gon["holiday"]= [...Array(10)].map((_,i) => (2015+i) + "-08-28");
Results:
(10) ["2015-08-28", "2016-08-28", "2017-08-28", "2018-08-28", "2019-08-28", "2020-08-28", "2021-08-28", "2022-08-28", "2023-08-28", "2024-08-28"]
You can use findIndex and provide it a function that would only match the day and month instead of the year, like so:
var gon = {};
gon["holiday"] = "*-08-28,*-09-25".split(",");
function pad(num) { return ("0" + num).slice(-2); }
function formatDate(date) { var d = new Date(date), dArr = [d.getFullYear(), pad(d.getMonth() + 1), pad(d.getDate())];return dArr.join('-');}
function calculateDays(first,last) {
var aDay = 24 * 60 * 60 * 1000,
daysDiff = parseInt((last.getTime()-first.getTime())/aDay,10);
if (daysDiff>0) {
for (var i = first.getTime(), lst = last.getTime(); i <= lst; i += aDay) {
var d = new Date(i);
console.log(d.getDay());
if (d.getDay() == 6 || d.getDay() == 0 // weekend
|| gon.holiday.findIndex((h)=>formatDate(d).replace(/[^-]+-/, '') == h.replace(/[^-]+-/, '')) != -1) {
daysDiff--;
}
}
}
return daysDiff;
}
I'm using a regular expression to remove the year, it removes the first occurrence of a dash and any characters before it.
You could have an array for holidays with fixed anniversaries in MM-DD format:
var fixedHols = ['08-28','09-25'];
another for those that move more or less randomly, such as easter, ramadan, diwali:
var movingHols = ['YYYY-MM-DD',...]
and another for rules–based holidays that is generated for the given year like the first Monday in May or the Tuesday following the first Monday in November or whatever, then test dates against them, e.g.
function isHoliday(date) {
let z = n => (n<10?'0':'')+n;
let fixedHols = ['08-28','09-25'];
let ymd = formatDate(date);
let md = ymd.slice(-5);
let movingHols = [ /* dates as YYY-MM-DD */ ];
let rulesHols = [ /* generate YYY-MM-DD for date.getFullYear() */ ];
// If date is in any array return true, otherwise return false
return [fixedHols, movingHols, rulesHols].some((hols, i) => hols.includes(i? ymd : md));
}
function formatDate(d) {
var z = n => (n<10?'0':'')+n;
return d.getFullYear()+'-'+z(d.getMonth()+1)+'-'+z(d.getDate());
}
[new Date(2018,7,27), // 27 Aug
new Date(2018,7,28), // 28 Aug
new Date(2018,7,29), // 29 Aug
new Date(2021,7,28), // 28 Aug
new Date(2018,8,25), // 25 Sep
new Date(2018,8,26)] // 26 Sep
.forEach(d =>
console.log(`Is ${formatDate(d)} a holiday? ${isHoliday(d)?'Yes':'No'}`)
);

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

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

How to get past 7 days and next 7 days in Javascript

I'm trying to get past 7 days and next 7 days date start data and end date using javascript date function.
For example : Today 31 march 2017 , When i click previous button, it will calculate from previous date ie: start and end date , (24 March 2017 to 30 March 2017) , again click previous (17 March 2017 to 23 March 2017)etcc..
Same thing will replicate for next button ..
I have tried the below things but its not working
function getPreviousWeek(){
ProHistoryCtrl.weekPrevcount = ProHistoryCtrl.weekPrevcount + 1;
ProHistoryCtrl.weekPrevious = (-6 * ProHistoryCtrl.weekPrevcount);
getByWeek();
}
function getNextWeek(){
ProHistoryCtrl.weekPrevcount = ProHistoryCtrl.weekPrevcount - 1;
ProHistoryCtrl.weekPrevious = (-6 * ProHistoryCtrl.weekPrevcount);
getByWeek();
}
function getByWeek(){
console.log("weekpreviouscount" + ProHistoryCtrl.weekPrevcount); //-6,-12,-18,-24
console.log("weekprevious" + ProHistoryCtrl.weekPrevious); //-6,-12,-18,-24
var d2 = new Date(); // 31.01.2017
var d1 = new Date(d2);
d1.setDate(d2.getDate() - 1); // 30.01.2017
var previousWeek = '';
var current_day = '';
console.log("d2date" + d1.getDate());
console.log("week2" + ProHistoryCtrl.weekPrevious)
previousWeek = new Date(d1);
previousWeek.setDate(d1.getDate() + ProHistoryCtrl.weekPrevious); // 30-13=17
current_day = new Date(d1); // 30.01.2017
current_day.setDate(d1.getDate() + ProHistoryCtrl.weekPrevious + 6); // 30-12+5=23
console.log("currentdayprevious" + ProHistoryCtrl.weekPrevious); //-6,-12,-18,-24
var previousWeekUTCTimestamp = Math.floor(previousWeek.getTime() / 1000);
var currentUTC = Math.floor(current_day.getTime() / 1000);
console.log("previousWeekUTCTimestamp" + previousWeekUTCTimestamp);
console.log("currentUTC" + currentUTC);
var sinceUTC = previousWeekUTCTimestamp;
var untilUTC = currentUTC;
}
Its first time comes correct 24-march 2017 to 30 march 2017 , next previous its comes 24-march to 18march2017
Any ideas ?please
The problem seems to be with your Maths, you get the previous week by subtracting 6 for each week and then subtracting an extra 1. This is fine for the first week where -6 -1 = -7, however for the second week this is (-6 * 2) - 1 = -13 but two weeks should be -14. The code that is incorrect is:
ProHistoryCtrl.weekPrevious = (-6 * ProHistoryCtrl.weekPrevcount);
d1.setDate(d2.getDate() - 1);
A solution would therefore be:
function getPreviousWeek(){
ProHistoryCtrl.weekPrevcount = ProHistoryCtrl.weekPrevcount + 1;
ProHistoryCtrl.weekPrevious = (-7 * ProHistoryCtrl.weekPrevcount);
getByWeek();
}
function getNextWeek(){
ProHistoryCtrl.weekPrevcount = ProHistoryCtrl.weekPrevcount - 1;
ProHistoryCtrl.weekPrevious = (-7 * ProHistoryCtrl.weekPrevcount);
getByWeek();
}
function getByWeek(){
var d2 = new Date(); // 31.01.2017
var d1 = new Date(d2);
d1.setDate(d2.getDate()); // 30.01.2017
var previousWeek = '';
var current_day = '';
previousWeek = new Date(d1);
previousWeek.setDate(d1.getDate() + ProHistoryCtrl.weekPrevious); // 30-13=17
current_day = new Date(d1); // 30.01.2017
current_day.setDate(d1.getDate() + ProHistoryCtrl.weekPrevious + 6); // 30-12+5=23
var previousWeekUTCTimestamp = Math.floor(previousWeek.getTime() / 1000);
var currentUTC = Math.floor(current_day.getTime() / 1000);
var sinceUTC = previousWeekUTCTimestamp;
var untilUTC = currentUTC;
}
Use this function. You don't need extra functions
var btn = document.querySelector("button")
Date.prototype.addDays = function(days) {
this.setDate(this.getDate() + parseInt(days));
return this;
};
function getDate(days) {
var date = new Date().addDays(days);
return date
}
btn.addEventListener("click", function() {
var pastSevenDays = getDate(-7)
var nextSevenDays = getDate(7)
// only date
console.log(pastSevenDays.toLocaleString().slice(0,10))
console.log(nextSevenDays.toLocaleString().slice(0,10))
}, false)
<button>Get Dates</button>

Iterating through timeslots

I'm having a little difficulty with the logic here, it's getting late and honestly, I'm stumped.
I need to loop through time slots.
var settings = {
startOfWeek:0, //0 = Sunday, 1 = Monday
timeSlotGap: 30,
minTime: "09:00:00",
maxTime: "17:30:00",
numSlots: 0
};
So I can specify a time slot gap, so if I was to iterate through the time slots (with a 30 minute gap) it would be:
09:00
09:30
10:00
10:30
Currently I have the following:
$(document).ready(function () {
getNumSlots(settings.minTime, settings.maxTime, settings.timeSlotGap);
for(var i = 1; i<=settings.numSlots; i++){
//I have no idea what I'm doing here
$('#calendar').append("<p>Timeslot:" + i +"</p>");
}
});
var WeekNo = moment().week();
var CurrentDate = getCurrentDate();
var WeekDay = moment().weekday();
var settings = {
startOfWeek:0, //0 = Sunday, 1 = Monday
timeSlotGap: 60,
minTime: "09:00:00",
maxTime: "17:30:00",
numSlots: 0
};
if(settings.startOfWeek == 0){
WeekDay = WeekDay - 1;
}
function getNumSlots(minTime, maxTime, timeSlotGap){
var minTimeSplit = minTime.split(":");
var hourStart = new Date("01/01/1900 " + minTime).getHours();
var hourEnd = new Date("01/01/1900 " + maxTime).getHours();
var minStart = new Date("01/01/1900 " + minTime).getMinutes();
var minEnd = new Date("01/01/1900 " + maxTime).getMinutes();
var diffHour = hourEnd - hourStart;
var diffMins = minEnd - minStart;
var slots = ((diffHour * 60) + diffMins) / timeSlotGap;
settings.numSlots = slots;
}
If it was as simple as looping through 30/60 minutes that wouldn't be a problem but since I can specify anything for the time slot i.e. 90 minutes it makes it a tad difficult.
To get the time slots you could use something like the following:
var settings = {
startOfWeek:0, //0 = Sunday, 1 = Monday
timeSlotGap: 30,
minTime: "09:00:00",
maxTime: "17:30:00",
numSlots: 0
};
function getTimeDate(time) {
var timeParts = time.split(':');
var d = new Date();
d.setHours(timeParts[0]);
d.setMinutes(timeParts[1]);
d.setSeconds(timeParts[2]);
return d;
}
function getTimeSlots(startDate, endDate, interval) {
var slots = [];
var intervalMillis = interval * 60 * 1000;
while (startDate < endDate) {
// So that you get "00" if we're on the hour.
var mins = (startDate.getMinutes() + '0').slice(0, 2);
slots.push(startDate.getHours() + ':' + mins);
startDate.setTime(startDate.getTime() + intervalMillis);
}
return slots;
}
var slots = getTimeSlots(
getTimeDate(settings.minTime), getTimeDate(settings.maxTime), settings.timeSlotGap
);
Here's an example JSFiddle.

How to calculate date difference in JavaScript? [duplicate]

This question already has answers here:
How to calculate number of days between two dates?
(42 answers)
Closed 3 months ago.
I want to calculate date difference in days, hours, minutes, seconds, milliseconds, nanoseconds. How can I do it?
Assuming you have two Date objects, you can just subtract them to get the difference in milliseconds:
var difference = date2 - date1;
From there, you can use simple arithmetic to derive the other values.
var DateDiff = {
inDays: function(d1, d2) {
var t2 = d2.getTime();
var t1 = d1.getTime();
return Math.floor((t2-t1)/(24*3600*1000));
},
inWeeks: function(d1, d2) {
var t2 = d2.getTime();
var t1 = d1.getTime();
return parseInt((t2-t1)/(24*3600*1000*7));
},
inMonths: function(d1, d2) {
var d1Y = d1.getFullYear();
var d2Y = d2.getFullYear();
var d1M = d1.getMonth();
var d2M = d2.getMonth();
return (d2M+12*d2Y)-(d1M+12*d1Y);
},
inYears: function(d1, d2) {
return d2.getFullYear()-d1.getFullYear();
}
}
var dString = "May, 20, 1984";
var d1 = new Date(dString);
var d2 = new Date();
document.write("<br />Number of <b>days</b> since "+dString+": "+DateDiff.inDays(d1, d2));
document.write("<br />Number of <b>weeks</b> since "+dString+": "+DateDiff.inWeeks(d1, d2));
document.write("<br />Number of <b>months</b> since "+dString+": "+DateDiff.inMonths(d1, d2));
document.write("<br />Number of <b>years</b> since "+dString+": "+DateDiff.inYears(d1, d2));
Code sample taken from here.
Another solution is convert difference to a new Date object and get that date's year(diff from 1970), month, day etc.
var date1 = new Date(2010, 6, 17);
var date2 = new Date(2013, 12, 18);
var diff = new Date(date2.getTime() - date1.getTime());
// diff is: Thu Jul 05 1973 04:00:00 GMT+0300 (EEST)
console.log(diff.getUTCFullYear() - 1970); // Gives difference as year
// 3
console.log(diff.getUTCMonth()); // Gives month count of difference
// 6
console.log(diff.getUTCDate() - 1); // Gives day count of difference
// 4
So difference is like "3 years and 6 months and 4 days". If you want to take difference in a human readable style, that can help you.
Expressions like "difference in days" are never as simple as they seem. If you have the following dates:
d1: 2011-10-15 23:59:00
d1: 2011-10-16 00:01:00
the difference in time is 2 minutes, should the "difference in days" be 1 or 0? Similar issues arise for any expression of the difference in months, years or whatever since years, months and days are of different lengths and different times (e.g. the day that daylight saving starts is 1 hour shorter than usual and two hours shorter than the day that it ends).
Here is a function for a difference in days that ignores the time, i.e. for the above dates it returns 1.
/*
Get the number of days between two dates - not inclusive.
"between" does not include the start date, so days
between Thursday and Friday is one, Thursday to Saturday
is two, and so on. Between Friday and the following Friday is 7.
e.g. getDaysBetweenDates( 22-Jul-2011, 29-jul-2011) => 7.
If want inclusive dates (e.g. leave from 1/1/2011 to 30/1/2011),
use date prior to start date (i.e. 31/12/2010 to 30/1/2011).
Only calculates whole days.
Assumes d0 <= d1
*/
function getDaysBetweenDates(d0, d1) {
var msPerDay = 8.64e7;
// Copy dates so don't mess them up
var x0 = new Date(d0);
var x1 = new Date(d1);
// Set to noon - avoid DST errors
x0.setHours(12,0,0);
x1.setHours(12,0,0);
// Round to remove daylight saving errors
return Math.round( (x1 - x0) / msPerDay );
}
This can be more concise:
/* Return number of days between d0 and d1.
** Returns positive if d0 < d1, otherwise negative.
**
** e.g. between 2000-02-28 and 2001-02-28 there are 366 days
** between 2015-12-28 and 2015-12-29 there is 1 day
** between 2015-12-28 23:59:59 and 2015-12-29 00:00:01 there is 1 day
** between 2015-12-28 00:00:01 and 2015-12-28 23:59:59 there are 0 days
**
** #param {Date} d0 - start date
** #param {Date} d1 - end date
** #returns {number} - whole number of days between d0 and d1
**
*/
function daysDifference(d0, d1) {
var diff = new Date(+d1).setHours(12) - new Date(+d0).setHours(12);
return Math.round(diff/8.64e7);
}
// Simple formatter
function formatDate(date){
return [date.getFullYear(),('0'+(date.getMonth()+1)).slice(-2),('0'+date.getDate()).slice(-2)].join('-');
}
// Examples
[[new Date(2000,1,28), new Date(2001,1,28)], // Leap year
[new Date(2001,1,28), new Date(2002,1,28)], // Not leap year
[new Date(2017,0,1), new Date(2017,1,1)]
].forEach(function(dates) {
document.write('From ' + formatDate(dates[0]) + ' to ' + formatDate(dates[1]) +
' is ' + daysDifference(dates[0],dates[1]) + ' days<br>');
});
<html lang="en">
<head>
<script>
function getDateDiff(time1, time2) {
var str1= time1.split('/');
var str2= time2.split('/');
// yyyy , mm , dd
var t1 = new Date(str1[2], str1[0]-1, str1[1]);
var t2 = new Date(str2[2], str2[0]-1, str2[1]);
var diffMS = t1 - t2;
console.log(diffMS + ' ms');
var diffS = diffMS / 1000;
console.log(diffS + ' ');
var diffM = diffS / 60;
console.log(diffM + ' minutes');
var diffH = diffM / 60;
console.log(diffH + ' hours');
var diffD = diffH / 24;
console.log(diffD + ' days');
alert(diffD);
}
//alert(getDateDiff('10/18/2013','10/14/2013'));
</script>
</head>
<body>
<input type="button"
onclick="getDateDiff('10/18/2013','10/14/2013')"
value="clickHere()" />
</body>
</html>
use Moment.js for all your JavaScript related date-time calculation
Answer to your question is:
var a = moment([2007, 0, 29]);
var b = moment([2007, 0, 28]);
a.diff(b) // 86400000
Complete details can be found here
adding to #paresh mayani 's answer, to work like Facebook - showing how much time has passed in sec/min/hours/weeks/months/years
var DateDiff = {
inSeconds: function(d1, d2) {
var t2 = d2.getTime();
var t1 = d1.getTime();
return parseInt((t2-t1)/1000);
},
inMinutes: function(d1, d2) {
var t2 = d2.getTime();
var t1 = d1.getTime();
return parseInt((t2-t1)/60000);
},
inHours: function(d1, d2) {
var t2 = d2.getTime();
var t1 = d1.getTime();
return parseInt((t2-t1)/3600000);
},
inDays: function(d1, d2) {
var t2 = d2.getTime();
var t1 = d1.getTime();
return parseInt((t2-t1)/(24*3600*1000));
},
inWeeks: function(d1, d2) {
var t2 = d2.getTime();
var t1 = d1.getTime();
return parseInt((t2-t1)/(24*3600*1000*7));
},
inMonths: function(d1, d2) {
var d1Y = d1.getFullYear();
var d2Y = d2.getFullYear();
var d1M = d1.getMonth();
var d2M = d2.getMonth();
return (d2M+12*d2Y)-(d1M+12*d1Y);
},
inYears: function(d1, d2) {
return d2.getFullYear()-d1.getFullYear();
}
}
var dString = "May, 20, 1984"; //will also get (Y-m-d H:i:s)
var d1 = new Date(dString);
var d2 = new Date();
var timeLaps = DateDiff.inSeconds(d1, d2);
var dateOutput = "";
if (timeLaps<60)
{
dateOutput = timeLaps+" seconds";
}
else
{
timeLaps = DateDiff.inMinutes(d1, d2);
if (timeLaps<60)
{
dateOutput = timeLaps+" minutes";
}
else
{
timeLaps = DateDiff.inHours(d1, d2);
if (timeLaps<24)
{
dateOutput = timeLaps+" hours";
}
else
{
timeLaps = DateDiff.inDays(d1, d2);
if (timeLaps<7)
{
dateOutput = timeLaps+" days";
}
else
{
timeLaps = DateDiff.inWeeks(d1, d2);
if (timeLaps<4)
{
dateOutput = timeLaps+" weeks";
}
else
{
timeLaps = DateDiff.inMonths(d1, d2);
if (timeLaps<12)
{
dateOutput = timeLaps+" months";
}
else
{
timeLaps = DateDiff.inYears(d1, d2);
dateOutput = timeLaps+" years";
}
}
}
}
}
}
alert (dateOutput);
With momentjs it's simple:
moment("2016-04-08").fromNow();
function DateDiff(date1, date2) {
date1.setHours(0);
date1.setMinutes(0, 0, 0);
date2.setHours(0);
date2.setMinutes(0, 0, 0);
var datediff = Math.abs(date1.getTime() - date2.getTime()); // difference
return parseInt(datediff / (24 * 60 * 60 * 1000), 10); //Convert values days and return value
}
var d1=new Date(2011,0,1); // jan,1 2011
var d2=new Date(); // now
var diff=d2-d1,sign=diff<0?-1:1,milliseconds,seconds,minutes,hours,days;
diff/=sign; // or diff=Math.abs(diff);
diff=(diff-(milliseconds=diff%1000))/1000;
diff=(diff-(seconds=diff%60))/60;
diff=(diff-(minutes=diff%60))/60;
days=(diff-(hours=diff%24))/24;
console.info(sign===1?"Elapsed: ":"Remains: ",
days+" days, ",
hours+" hours, ",
minutes+" minutes, ",
seconds+" seconds, ",
milliseconds+" milliseconds.");
I think this should do it.
let today = new Date();
let form_date=new Date('2019-10-23')
let difference=form_date>today ? form_date-today : today-form_date
let diff_days=Math.floor(difference/(1000*3600*24))
based on javascript runtime prototype implementation you can use simple arithmetic to subtract dates as in bellow
var sep = new Date(2020, 07, 31, 23, 59, 59);
var today = new Date();
var diffD = Math.floor((sep - today) / (1000 * 60 * 60 * 24));
console.log('Day Diff: '+diffD);
the difference return answer as milliseconds, then you have to convert it by division:
by 1000 to convert to second
by 1000×60 convert to minute
by 1000×60×60 convert to hour
by 1000×60×60×24 convert to day
function DateDiff(b, e)
{
let
endYear = e.getFullYear(),
endMonth = e.getMonth(),
years = endYear - b.getFullYear(),
months = endMonth - b.getMonth(),
days = e.getDate() - b.getDate();
if (months < 0)
{
years--;
months += 12;
}
if (days < 0)
{
months--;
days += new Date(endYear, endMonth, 0).getDate();
}
return [years, months, days];
}
[years, months, days] = DateDiff(
new Date("October 21, 1980"),
new Date("July 11, 2017")); // 36 8 20
Sorry but flat millisecond calculation is not reliable
Thanks for all the responses, but few of the functions I tried are failing either on
1. A date near today's date
2. A date in 1970 or
3. A date in a leap year.
Approach that best worked for me and covers all scenario e.g. leap year, near date in 1970, feb 29 etc.
var someday = new Date("8/1/1985");
var today = new Date();
var years = today.getFullYear() - someday.getFullYear();
// Reset someday to the current year.
someday.setFullYear(today.getFullYear());
// Depending on when that day falls for this year, subtract 1.
if (today < someday)
{
years--;
}
document.write("Its been " + years + " full years.");
This code will return the difference between two dates in days:
const previous_date = new Date("2019-12-23");
const current_date = new Date();
const current_year = current_date.getFullYear();
const previous_date_year =
previous_date.getFullYear();
const difference_in_years = current_year -
previous_date_year;
let months = current_date.getMonth();
months = months + 1; // for making the indexing
// of months from 1
for(let i = 0; i < difference_in_years; i++){
months = months + 12;
}
let days = current_date.getDate();
days = days + (months * 30.417);
console.log(`The days between ${current_date} and
${previous_date} are : ${days} (approximately)`);
If you are using moment.js then it is pretty simple to find date difference.
var now = "04/09/2013 15:00:00";
var then = "04/09/2013 14:20:30";
moment.utc(moment(now,"DD/MM/YYYY HH:mm:ss").diff(moment(then,"DD/MM/YYYY HH:mm:ss"))).format("HH:mm:ss")
This is how you can implement difference between dates without a framework.
function getDateDiff(dateOne, dateTwo) {
if(dateOne.charAt(2)=='-' & dateTwo.charAt(2)=='-'){
dateOne = new Date(formatDate(dateOne));
dateTwo = new Date(formatDate(dateTwo));
}
else{
dateOne = new Date(dateOne);
dateTwo = new Date(dateTwo);
}
let timeDiff = Math.abs(dateOne.getTime() - dateTwo.getTime());
let diffDays = Math.ceil(timeDiff / (1000 * 3600 * 24));
let diffMonths = Math.ceil(diffDays/31);
let diffYears = Math.ceil(diffMonths/12);
let message = "Difference in Days: " + diffDays + " " +
"Difference in Months: " + diffMonths+ " " +
"Difference in Years: " + diffYears;
return message;
}
function formatDate(date) {
return date.split('-').reverse().join('-');
}
console.log(getDateDiff("23-04-2017", "23-04-2018"));
function daysInMonth (month, year) {
return new Date(year, month, 0).getDate();
}
function getduration(){
let A= document.getElementById("date1_id").value
let B= document.getElementById("date2_id").value
let C=Number(A.substring(3,5))
let D=Number(B.substring(3,5))
let dif=D-C
let arr=[];
let sum=0;
for (let i=0;i<dif+1;i++){
sum+=Number(daysInMonth(i+C,2019))
}
let sum_alter=0;
for (let i=0;i<dif;i++){
sum_alter+=Number(daysInMonth(i+C,2019))
}
let no_of_month=(Number(B.substring(3,5)) - Number(A.substring(3,5)))
let days=[];
if ((Number(B.substring(3,5)) - Number(A.substring(3,5)))>0||Number(B.substring(0,2)) - Number(A.substring(0,2))<0){
days=Number(B.substring(0,2)) - Number(A.substring(0,2)) + sum_alter
}
if ((Number(B.substring(3,5)) == Number(A.substring(3,5)))){
console.log(Number(B.substring(0,2)) - Number(A.substring(0,2)) + sum_alter)
}
time_1=[]; time_2=[]; let hour=[];
time_1=document.getElementById("time1_id").value
time_2=document.getElementById("time2_id").value
if (time_1.substring(0,2)=="12"){
time_1="00:00:00 PM"
}
if (time_1.substring(9,11)==time_2.substring(9,11)){
hour=Math.abs(Number(time_2.substring(0,2)) - Number(time_1.substring(0,2)))
}
if (time_1.substring(9,11)!=time_2.substring(9,11)){
hour=Math.abs(Number(time_2.substring(0,2)) - Number(time_1.substring(0,2)))+12
}
let min=Math.abs(Number(time_1.substring(3,5))-Number(time_2.substring(3,5)))
document.getElementById("duration_id").value=days +" days "+ hour+" hour " + min+" min "
}
<input type="text" id="date1_id" placeholder="28/05/2019">
<input type="text" id="date2_id" placeholder="29/06/2019">
<br><br>
<input type="text" id="time1_id" placeholder="08:01:00 AM">
<input type="text" id="time2_id" placeholder="00:00:00 PM">
<br><br>
<button class="text" onClick="getduration()">Submit </button>
<br><br>
<input type="text" id="duration_id" placeholder="days hour min">
var date1 = new Date("06/30/2019");
var date2 = new Date("07/30/2019");
// To calculate the time difference of two dates
var Difference_In_Time = date2.getTime() - date1.getTime();
// To calculate the no. of days between two dates
var Difference_In_Days = Difference_In_Time / (1000 * 3600 * 24);
//To display the final no. of days (result)
document.write("Total number of days between dates <br>"
+ date1 + "<br> and <br>"
+ date2 + " is: <br> "
+ Difference_In_Days);
this should work just fine if you just need to show what time left, since JavaScript uses frames for its time you'll have get your End Time - The Time RN after that we can divide it by 1000 since apparently 1000 frames = 1 seconds, after that you can use the basic math of time, but there's still a problem to this code, since the calculation is static, it can't compensate for the different day total in a year (360/365/366), the bunch of IF after the calculation is to make it null if the time is lower than 0, hope this helps even though it's not exactly what you're asking :)
var now = new Date();
var end = new Date("End Time");
var total = (end - now) ;
var totalD = Math.abs(Math.floor(total/1000));
var years = Math.floor(totalD / (365*60*60*24));
var months = Math.floor((totalD - years*365*60*60*24) / (30*60*60*24));
var days = Math.floor((totalD - years*365*60*60*24 - months*30*60*60*24)/ (60*60*24));
var hours = Math.floor((totalD - years*365*60*60*24 - months*30*60*60*24 - days*60*60*24)/ (60*60));
var minutes = Math.floor((totalD - years*365*60*60*24 - months*30*60*60*24 - days*60*60*24 - hours*60*60)/ (60));
var seconds = Math.floor(totalD - years*365*60*60*24 - months*30*60*60*24 - days*60*60*24 - hours*60*60 - minutes*60);
var Y = years < 1 ? "" : years + " Years ";
var M = months < 1 ? "" : months + " Months ";
var D = days < 1 ? "" : days + " Days ";
var H = hours < 1 ? "" : hours + " Hours ";
var I = minutes < 1 ? "" : minutes + " Minutes ";
var S = seconds < 1 ? "" : seconds + " Seconds ";
var A = years == 0 && months == 0 && days == 0 && hours == 0 && minutes == 0 && seconds == 0 ? "Sending" : " Remaining";
document.getElementById('txt').innerHTML = Y + M + D + H + I + S + A;
Ok, there are a bunch of ways you can do that.
Yes, you can use plain old JS. Just try:
let dt1 = new Date()
let dt2 = new Date()
Let's emulate passage using Date.prototype.setMinutes and make sure we are in range.
dt1.setMinutes(7)
dt2.setMinutes(42)
console.log('Elapsed seconds:',(dt2-dt1)/1000)
Alternatively you could use some library like js-joda, where you can easily do things like this (directly from docs):
var dt1 = LocalDateTime.parse("2016-02-26T23:55:42.123");
var dt2 = dt1
.plusYears(6)
.plusMonths(12)
.plusHours(2)
.plusMinutes(42)
.plusSeconds(12);
// obtain the duration between the two dates
dt1.until(dt2, ChronoUnit.YEARS); // 7
dt1.until(dt2, ChronoUnit.MONTHS); // 84
dt1.until(dt2, ChronoUnit.WEEKS); // 356
dt1.until(dt2, ChronoUnit.DAYS); // 2557
dt1.until(dt2, ChronoUnit.HOURS); // 61370
dt1.until(dt2, ChronoUnit.MINUTES); // 3682242
dt1.until(dt2, ChronoUnit.SECONDS); // 220934532
There are plenty more libraries ofc, but js-joda has an added bonus of being available also in Java, where it has been extensively tested. All those tests have been migrated to js-joda, it's also immutable.
I made a below function to get the difference between now and "2021-02-26T21:50:42.123".
The difference return answer as milliseconds, so I convert it by using this formula:
(1000 * 3600 * 24).
function getDiff(dateAcquired) {
let calDiff = Math.floor(
(new Date() - new Date(dateAcquired)) / (1000 * 3600 * 24)
);
return calDiff;
}
console.log(getDiff("2021-02-26T21:50:42.123"));
Can be useful :
const date_diff = (date1, date2) => Math.ceil(Math.abs(date1 - date2)/24 * 60 * 60 * 1000)
or
const date_diff = (date1, date2) => Math.ceil(Math.abs(date1 - date2)/86400000)
where 24 * 60 * 60 * 1000 is (day * minutes * seconds * milliseconds) = 86400000 milliseconds in one day
Thank you
// the idea is to get time left for new year.
// Not considering milliseconds as of now, but that
// can be done
var newYear = '1 Jan 2023';
const secondsInAMin = 60;
const secondsInAnHour = 60 * secondsInAMin;
const secondsInADay = 24 * secondsInAnHour;
function DateDiffJs() {
var newYearDate = new Date(newYear);
var currDate = new Date();
var remainingSecondsInDateDiff = (newYearDate - currDate) / 1000;
var days = Math.floor(remainingSecondsInDateDiff / secondsInADay);
var remainingSecondsAfterDays = remainingSecondsInDateDiff - (days * secondsInADay);
var hours = Math.floor(remainingSecondsAfterDays / secondsInAnHour);
var remainingSecondsAfterhours = remainingSecondsAfterDays - (hours * secondsInAnHour);
var mins = Math.floor(remainingSecondsAfterhours / secondsInAMin);
var seconds = Math.floor(remainingSecondsAfterhours - (mins * secondsInAMin));
console.log(`days :: ${days}`)
console.log(`hours :: ${hours}`)
console.log(`mins :: ${mins}`)
console.log(`seconds :: ${seconds}`)
}
DateDiffJs();

Categories

Resources