Find the difference between two dates - javascript

How can i find the difference between two dates in this format
Year, Month (Must be < 12 if > 12 the Year++), Days ( Must be < 30 if > 30 then month++), Hours (must be < 24 if > 24 then day++)
i wont have a format like this
year 3,
month 34 (i will calc this 34 in years),
dasy 345 ( an this value too)
i have this code
http://jsfiddle.net/AQSWu/
var currentTo = new Date(2015, 6, 1),
currentFrom = new Date(2013,11,1),
year = currentTo.getFullYear() - currentFrom.getFullYear(),
m1 = currentTo.getMonth() + 1,
m2 = currentFrom.getMonth() + 1,
month = m1 <= m2 ? (12 - m2) + m1 : m1 - m2;
alert("From: " + currentFrom);
alert("To :" + currentTo);
if (currentTo.getDate() < currentFrom.getDate()) {
month = month - 1;
}
if (month >= 12){ month = 0; }
alert(year + ' ' + month);
but i have no idea how i can calc days an hours

Don't substract year, month, day etc separately, but just get the difference between the dates (in milliseconds) and then output that in a format (or unit) that you want:
var currentTo = new Date(2015, 6, 1),
currentFrom = new Date(2013,11,1),
difference = currentTo - currentFrom; // number conversion is implicit
var hours = difference / 3600000; // ms -> h
// now do your maths

Related

How can I get the future month based on the current date? [duplicate]

How to get the difference between two dates in years, months, and days in JavaScript, like: 10th of April 2010 was 3 years, x month and y days ago?
There are lots of solutions, but they only offer the difference in the format of either days OR months OR years, or they are not correct (meaning not taking care of actual number of days in a month or leap years, etc). Is it really that difficult to do that?
I've had a look at:
http://momentjs.com/ -> can only output the difference in either years, months, OR days
http://www.javascriptkit.com/javatutors/datedifference.shtml
http://www.javascriptkit.com/jsref/date.shtml
http://timeago.yarp.com/
www.stackoverflow.com -> Search function
In php it is easy, but unfortunately I can only use client-side script on that project. Any library or framework that can do it would be fine, too.
Here are a list of expected outputs for date differences:
//Expected output should be: "1 year, 5 months".
diffDate(new Date('2014-05-10'), new Date('2015-10-10'));
//Expected output should be: "1 year, 4 months, 29 days".
diffDate(new Date('2014-05-10'), new Date('2015-10-09'));
//Expected output should be: "1 year, 3 months, 30 days".
diffDate(new Date('2014-05-10'), new Date('2015-09-09'));
//Expected output should be: "9 months, 27 days".
diffDate(new Date('2014-05-10'), new Date('2015-03-09'));
//Expected output should be: "1 year, 9 months, 28 days".
diffDate(new Date('2014-05-10'), new Date('2016-03-09'));
//Expected output should be: "1 year, 10 months, 1 days".
diffDate(new Date('2014-05-10'), new Date('2016-03-11'));
How precise do you need to be? If you do need to take into account common years and leap years, and the exact difference in days between months then you'll have to write something more advanced but for a basic and rough calculation this should do the trick:
today = new Date()
past = new Date(2010,05,01) // remember this is equivalent to 06 01 2010
//dates in js are counted from 0, so 05 is june
function calcDate(date1,date2) {
var diff = Math.floor(date1.getTime() - date2.getTime());
var day = 1000 * 60 * 60 * 24;
var days = Math.floor(diff/day);
var months = Math.floor(days/31);
var years = Math.floor(months/12);
var message = date2.toDateString();
message += " was "
message += days + " days "
message += months + " months "
message += years + " years ago \n"
return message
}
a = calcDate(today,past)
console.log(a) // returns Tue Jun 01 2010 was 1143 days 36 months 3 years ago
Keep in mind that this is imprecise, in order to calculate the date with full precision one would have to have a calendar and know if a year is a leap year or not, also the way I'm calculating the number of months is only approximate.
But you can improve it easily.
Actually, there's a solution with a moment.js plugin and it's very easy.
You might use moment.js
Don't reinvent the wheel again.
Just plug Moment.js Date Range Plugin.
Example:
var starts = moment('2014-02-03 12:53:12');
var ends = moment();
var duration = moment.duration(ends.diff(starts));
// with ###moment precise date range plugin###
// it will tell you the difference in human terms
var diff = moment.preciseDiff(starts, ends, true);
// example: { "years": 2, "months": 7, "days": 0, "hours": 6, "minutes": 29, "seconds": 17, "firstDateWasLater": false }
// or as string:
var diffHuman = moment.preciseDiff(starts, ends);
// example: 2 years 7 months 6 hours 29 minutes 17 seconds
document.getElementById('output1').innerHTML = JSON.stringify(diff)
document.getElementById('output2').innerHTML = diffHuman
<html>
<head>
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.14.1/moment.min.js"></script>
<script src="https://raw.githubusercontent.com/codebox/moment-precise-range/master/moment-precise-range.js"></script>
</head>
<body>
<h2>Difference between "NOW and 2014-02-03 12:53:12"</h2>
<span id="output1"></span>
<br />
<span id="output2"></span>
</body>
</html>
Modified this to be a lot more accurate. It will convert dates to a 'YYYY-MM-DD' format, ignoring HH:MM:SS, and takes an optional endDate or uses the current date, and doesn't care about the order of the values.
function dateDiff(startingDate, endingDate) {
let startDate = new Date(new Date(startingDate).toISOString().substr(0, 10));
if (!endingDate) {
endingDate = new Date().toISOString().substr(0, 10); // need date in YYYY-MM-DD format
}
let endDate = new Date(endingDate);
if (startDate > endDate) {
const swap = startDate;
startDate = endDate;
endDate = swap;
}
const startYear = startDate.getFullYear();
const february = (startYear % 4 === 0 && startYear % 100 !== 0) || startYear % 400 === 0 ? 29 : 28;
const daysInMonth = [31, february, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31];
let yearDiff = endDate.getFullYear() - startYear;
let monthDiff = endDate.getMonth() - startDate.getMonth();
if (monthDiff < 0) {
yearDiff--;
monthDiff += 12;
}
let dayDiff = endDate.getDate() - startDate.getDate();
if (dayDiff < 0) {
if (monthDiff > 0) {
monthDiff--;
} else {
yearDiff--;
monthDiff = 11;
}
dayDiff += daysInMonth[startDate.getMonth()];
}
return yearDiff + 'Y ' + monthDiff + 'M ' + dayDiff + 'D';
}
// Examples
let dates = [
['2019-05-10','2019-05-10'], // 0Y 0M 0D
['2019-05-09','2019-05-10'], // 0Y 0M 1D
['2018-05-09','2019-05-10'], // 1Y 0M 1D
['2018-05-18','2019-05-10'], // 0Y 11M 23D
['2019-01-09','2019-05-10'], // 0Y 4M 1D
['2019-02-10','2019-05-10'], // 0Y 3M 0D
['2019-02-11','2019-05-10'], // 0Y 2M 27D
['2016-02-11','2019-05-10'], // 3Y 2M 28D - leap year
['1972-11-30','2019-05-10'], // 46Y 5M 10D
['2016-02-11','2017-02-11'], // 1Y 0M 0D
['2016-02-11','2016-03-10'], // 0Y 0M 28D - leap year
['2100-02-11','2100-03-10'], // 0Y 0M 27D - not a leap year
['2017-02-11','2016-02-11'], // 1Y 0M 0D - swapped dates to return correct result
[new Date() - 1000 * 60 * 60 * 24] // 0Y 0M 1D - uses current date
].forEach(([s, e]) => console.log(dateDiff(s, e)));
Older less accurate but much simpler version
#RajeevPNadig's answer was what I was looking for, but his code returns incorrect values as written. This code is not very accurate because it assumes that the sequence of dates from 1 January 1970 is the same as any other sequence of the same number of days. E.g. it calculates the difference from 1 July to 1 September (62 days) as 0Y 2M 3D and not 0Y 2M 0D because 1 Jan 1970 plus 62 days is 3 March.
// startDate must be a date string
function dateAgo(date) {
var startDate = new Date(date);
var diffDate = new Date(new Date() - startDate);
return ((diffDate.toISOString().slice(0, 4) - 1970) + "Y " +
diffDate.getMonth() + "M " + (diffDate.getDate()-1) + "D");
}
Then you can use it like this:
// based on a current date of 2018-03-09
dateAgo('1972-11-30'); // "45Y 3M 9D"
dateAgo('2017-03-09'); // "1Y 0M 0D"
dateAgo('2018-01-09'); // "0Y 2M 0D"
dateAgo('2018-02-09'); // "0Y 0M 28D" -- a little odd, but not wrong
dateAgo('2018-02-01'); // "0Y 1M 5D" -- definitely "feels" wrong
dateAgo('2018-03-09'); // "0Y 0M 0D"
If your use case is just date strings, then this works okay if you just want a quick and dirty 4 liner.
I used this simple code to get difference in Years, Months, days with current date.
var sdt = new Date('1972-11-30');
var difdt = new Date(new Date() - sdt);
alert((difdt.toISOString().slice(0, 4) - 1970) + "Y " + (difdt.getMonth()+1) + "M " + difdt.getDate() + "D");
I think you are looking for the same thing that I wanted. I tried to do this using the difference in milliseconds that javascript provides, but those results do not work in the real world of dates. If you want the difference between Feb 1, 2016 and January 31, 2017 the result I would want is 1 year, 0 months, and 0 days. Exactly one year (assuming you count the last day as a full day, like in a lease for an apartment). However, the millisecond approach would give you 1 year 0 months and 1 day, since the date range includes a leap year. So here is the code I used in javascript for my adobe form (you can name the fields): (edited, there was an error that I corrected)
var f1 = this.getField("LeaseExpiration");
var g1 = this.getField("LeaseStart");
var end = f1.value
var begin = g1.value
var e = new Date(end);
var b = new Date(begin);
var bMonth = b.getMonth();
var bYear = b.getFullYear();
var eYear = e.getFullYear();
var eMonth = e.getMonth();
var bDay = b.getDate();
var eDay = e.getDate() + 1;
if ((eMonth == 0)||(eMonth == 2)||(eMonth == 4)|| (eMonth == 6) || (eMonth == 7) ||(eMonth == 9)||(eMonth == 11))
{
var eDays = 31;
}
if ((eMonth == 3)||(eMonth == 5)||(eMonth == 8)|| (eMonth == 10))
{
var eDays = 30;
}
if (eMonth == 1&&((eYear % 4 == 0) && (eYear % 100 != 0)) || (eYear % 400 == 0))
{
var eDays = 29;
}
if (eMonth == 1&&((eYear % 4 != 0) || (eYear % 100 == 0)))
{
var eDays = 28;
}
if ((bMonth == 0)||(bMonth == 2)||(bMonth == 4)|| (bMonth == 6) || (bMonth == 7) ||(bMonth == 9)||(bMonth == 11))
{
var bDays = 31;
}
if ((bMonth == 3)||(bMonth == 5)||(bMonth == 8)|| (bMonth == 10))
{
var bDays = 30;
}
if (bMonth == 1&&((bYear % 4 == 0) && (bYear % 100 != 0)) || (bYear % 400 == 0))
{
var bDays = 29;
}
if (bMonth == 1&&((bYear % 4 != 0) || (bYear % 100 == 0)))
{
var bDays = 28;
}
var FirstMonthDiff = bDays - bDay + 1;
if (eDay - bDay < 0)
{
eMonth = eMonth - 1;
eDay = eDay + eDays;
}
var daysDiff = eDay - bDay;
if(eMonth - bMonth < 0)
{
eYear = eYear - 1;
eMonth = eMonth + 12;
}
var monthDiff = eMonth - bMonth;
var yearDiff = eYear - bYear;
if (daysDiff == eDays)
{
daysDiff = 0;
monthDiff = monthDiff + 1;
if (monthDiff == 12)
{
monthDiff = 0;
yearDiff = yearDiff + 1;
}
}
if ((FirstMonthDiff != bDays)&&(eDay - 1 == eDays))
{
daysDiff = FirstMonthDiff;
}
event.value = yearDiff + " Year(s)" + " " + monthDiff + " month(s) " + daysDiff + " days(s)"
I have created, yet another one, function for this purpose:
function dateDiff(date) {
date = date.split('-');
var today = new Date();
var year = today.getFullYear();
var month = today.getMonth() + 1;
var day = today.getDate();
var yy = parseInt(date[0]);
var mm = parseInt(date[1]);
var dd = parseInt(date[2]);
var years, months, days;
// months
months = month - mm;
if (day < dd) {
months = months - 1;
}
// years
years = year - yy;
if (month * 100 + day < mm * 100 + dd) {
years = years - 1;
months = months + 12;
}
// days
days = Math.floor((today.getTime() - (new Date(yy + years, mm + months - 1, dd)).getTime()) / (24 * 60 * 60 * 1000));
//
return {years: years, months: months, days: days};
}
Doesn't require any 3rd party libraries. Takes one argument -- date in YYYY-MM-DD format.
https://gist.github.com/lemmon/d27c2d4a783b1cf72d1d1cc243458d56
With dayjs we did it in that way:
export const getAgeDetails = (oldDate: dayjs.Dayjs, newDate: dayjs.Dayjs) => {
const years = newDate.diff(oldDate, 'year');
const months = newDate.diff(oldDate, 'month') - years * 12;
const days = newDate.diff(oldDate.add(years, 'year').add(months, 'month'), 'day');
return {
years,
months,
days,
allDays: newDate.diff(oldDate, 'day'),
};
};
It calculates it perfectly including leap years and different month amount of days.
For quick and easy use I wrote this function some time ago. It returns the diff between two dates in a nice format. Feel free to use it (tested on webkit).
/**
* Function to print date diffs.
*
* #param {Date} fromDate: The valid start date
* #param {Date} toDate: The end date. Can be null (if so the function uses "now").
* #param {Number} levels: The number of details you want to get out (1="in 2 Months",2="in 2 Months, 20 Days",...)
* #param {Boolean} prefix: adds "in" or "ago" to the return string
* #return {String} Diffrence between the two dates.
*/
function getNiceTime(fromDate, toDate, levels, prefix){
var lang = {
"date.past": "{0} ago",
"date.future": "in {0}",
"date.now": "now",
"date.year": "{0} year",
"date.years": "{0} years",
"date.years.prefixed": "{0} years",
"date.month": "{0} month",
"date.months": "{0} months",
"date.months.prefixed": "{0} months",
"date.day": "{0} day",
"date.days": "{0} days",
"date.days.prefixed": "{0} days",
"date.hour": "{0} hour",
"date.hours": "{0} hours",
"date.hours.prefixed": "{0} hours",
"date.minute": "{0} minute",
"date.minutes": "{0} minutes",
"date.minutes.prefixed": "{0} minutes",
"date.second": "{0} second",
"date.seconds": "{0} seconds",
"date.seconds.prefixed": "{0} seconds",
},
langFn = function(id,params){
var returnValue = lang[id] || "";
if(params){
for(var i=0;i<params.length;i++){
returnValue = returnValue.replace("{"+i+"}",params[i]);
}
}
return returnValue;
},
toDate = toDate ? toDate : new Date(),
diff = fromDate - toDate,
past = diff < 0 ? true : false,
diff = diff < 0 ? diff * -1 : diff,
date = new Date(new Date(1970,0,1,0).getTime()+diff),
returnString = '',
count = 0,
years = (date.getFullYear() - 1970);
if(years > 0){
var langSingle = "date.year" + (prefix ? "" : ""),
langMultiple = "date.years" + (prefix ? ".prefixed" : "");
returnString += (count > 0 ? ', ' : '') + (years > 1 ? langFn(langMultiple,[years]) : langFn(langSingle,[years]));
count ++;
}
var months = date.getMonth();
if(count < levels && months > 0){
var langSingle = "date.month" + (prefix ? "" : ""),
langMultiple = "date.months" + (prefix ? ".prefixed" : "");
returnString += (count > 0 ? ', ' : '') + (months > 1 ? langFn(langMultiple,[months]) : langFn(langSingle,[months]));
count ++;
} else {
if(count > 0)
count = 99;
}
var days = date.getDate() - 1;
if(count < levels && days > 0){
var langSingle = "date.day" + (prefix ? "" : ""),
langMultiple = "date.days" + (prefix ? ".prefixed" : "");
returnString += (count > 0 ? ', ' : '') + (days > 1 ? langFn(langMultiple,[days]) : langFn(langSingle,[days]));
count ++;
} else {
if(count > 0)
count = 99;
}
var hours = date.getHours();
if(count < levels && hours > 0){
var langSingle = "date.hour" + (prefix ? "" : ""),
langMultiple = "date.hours" + (prefix ? ".prefixed" : "");
returnString += (count > 0 ? ', ' : '') + (hours > 1 ? langFn(langMultiple,[hours]) : langFn(langSingle,[hours]));
count ++;
} else {
if(count > 0)
count = 99;
}
var minutes = date.getMinutes();
if(count < levels && minutes > 0){
var langSingle = "date.minute" + (prefix ? "" : ""),
langMultiple = "date.minutes" + (prefix ? ".prefixed" : "");
returnString += (count > 0 ? ', ' : '') + (minutes > 1 ? langFn(langMultiple,[minutes]) : langFn(langSingle,[minutes]));
count ++;
} else {
if(count > 0)
count = 99;
}
var seconds = date.getSeconds();
if(count < levels && seconds > 0){
var langSingle = "date.second" + (prefix ? "" : ""),
langMultiple = "date.seconds" + (prefix ? ".prefixed" : "");
returnString += (count > 0 ? ', ' : '') + (seconds > 1 ? langFn(langMultiple,[seconds]) : langFn(langSingle,[seconds]));
count ++;
} else {
if(count > 0)
count = 99;
}
if(prefix){
if(returnString == ""){
returnString = langFn("date.now");
} else if(past)
returnString = langFn("date.past",[returnString]);
else
returnString = langFn("date.future",[returnString]);
}
return returnString;
}
If you are using date-fns and if you dont want to install the Moment.js or the moment-precise-range-plugin. You can use the following date-fns function to get the same result as moment-precise-range-plugin
intervalToDuration({
start: new Date(),
end: new Date("24 Jun 2020")
})
This will give output in a JSON object like below
{
"years": 0,
"months": 0,
"days": 0,
"hours": 19,
"minutes": 35,
"seconds": 24
}
Live Example https://stackblitz.com/edit/react-wvxvql
Link to Documentation https://date-fns.org/v2.14.0/docs/intervalToDuration
Some math is in order.
You can subtract one Date object from another in Javascript, and you'll get the difference between them in milisseconds. From this result you can extract the other parts you want (days, months etc.)
For example:
var a = new Date(2010, 10, 1);
var b = new Date(2010, 9, 1);
var c = a - b; // c equals 2674800000,
// the amount of milisseconds between September 1, 2010
// and August 1, 2010.
Now you can get any part you want. For example, how many days have elapsed between the two dates:
var days = (a - b) / (60 * 60 * 24 * 1000);
// 60 * 60 * 24 * 1000 is the amount of milisseconds in a day.
// the variable days now equals 30.958333333333332.
That's almost 31 days. You can then round down for 30 days, and use whatever remained to get the amounts of hours, minutes etc.
Get the difference between two dates in a human way
This function is capable of returning natural-language-like text. Use it to get responses like:
"4 years, 1 month and 11 days"
"1 year and 2 months"
"11 months and 20 days"
"12 days"
IMPORTANT: date-fns is a dependency
Just copy the code below and plug in a past date into our getElapsedTime function! It will compare the entered date against the present time and return your human-like responses.
import * as dateFns from "https://cdn.skypack.dev/date-fns#2.22.1";
function getElapsedTime(pastDate) {
const duration = dateFns.intervalToDuration({
start: new Date(pastDate),
end: new Date(),
});
let [years, months, days] = ["", "", ""];
if (duration.years > 0) {
years = duration.years === 1 ? "1 year" : `${duration.years} years`;
}
if (duration.months > 0) {
months = duration.months === 1 ? "1 month" : `${duration.months} months`;
}
if (duration.days > 0) {
days = duration.days === 1 ? "1 day" : `${duration.days} days`;
}
let response = [years, months, days].filter(Boolean);
switch (response.length) {
case 3:
response[1] += " and";
response[0] += ",";
break;
case 2:
response[0] += " and";
break;
}
return response.join(" ");
}
Yet another solution, based on some PHP code.
The strtotime function, also based on PHP, can be found here: http://phpjs.org/functions/strtotime/.
Date.dateDiff = function(d1, d2) {
d1 /= 1000;
d2 /= 1000;
if (d1 > d2) d2 = [d1, d1 = d2][0];
var diffs = {
year: 0,
month: 0,
day: 0,
hour: 0,
minute: 0,
second: 0
}
$.each(diffs, function(interval) {
while (d2 >= (d3 = Date.strtotime('+1 '+interval, d1))) {
d1 = d3;
++diffs[interval];
}
});
return diffs;
};
Usage:
> d1 = new Date(2000, 0, 1)
Sat Jan 01 2000 00:00:00 GMT+0100 (CET)
> d2 = new Date(2013, 9, 6)
Sun Oct 06 2013 00:00:00 GMT+0200 (CEST)
> Date.dateDiff(d1, d2)
Object {
day: 5
hour: 0
minute: 0
month: 9
second: 0
year: 13
}
Very old thread, I know, but here's my contribution, as the thread is not solved yet.
It takes leap years into consideration and does not asume any fixed number of days per month or year.
It might be flawed in border cases as I haven't tested it thoroughly, but it works for all the dates provided in the original question, thus I'm confident.
function calculate() {
var fromDate = document.getElementById('fromDate').value;
var toDate = document.getElementById('toDate').value;
try {
document.getElementById('result').innerHTML = '';
var result = getDateDifference(new Date(fromDate), new Date(toDate));
if (result && !isNaN(result.years)) {
document.getElementById('result').innerHTML =
result.years + ' year' + (result.years == 1 ? ' ' : 's ') +
result.months + ' month' + (result.months == 1 ? ' ' : 's ') + 'and ' +
result.days + ' day' + (result.days == 1 ? '' : 's');
}
} catch (e) {
console.error(e);
}
}
function getDateDifference(startDate, endDate) {
if (startDate > endDate) {
console.error('Start date must be before end date');
return null;
}
var startYear = startDate.getFullYear();
var startMonth = startDate.getMonth();
var startDay = startDate.getDate();
var endYear = endDate.getFullYear();
var endMonth = endDate.getMonth();
var endDay = endDate.getDate();
// We calculate February based on end year as it might be a leep year which might influence the number of days.
var february = (endYear % 4 == 0 && endYear % 100 != 0) || endYear % 400 == 0 ? 29 : 28;
var daysOfMonth = [31, february, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31];
var startDateNotPassedInEndYear = (endMonth < startMonth) || endMonth == startMonth && endDay < startDay;
var years = endYear - startYear - (startDateNotPassedInEndYear ? 1 : 0);
var months = (12 + endMonth - startMonth - (endDay < startDay ? 1 : 0)) % 12;
// (12 + ...) % 12 makes sure index is always between 0 and 11
var days = startDay <= endDay ? endDay - startDay : daysOfMonth[(12 + endMonth - 1) % 12] - startDay + endDay;
return {
years: years,
months: months,
days: days
};
}
<p><input type="text" name="fromDate" id="fromDate" placeholder="yyyy-mm-dd" value="1999-02-28" /></p>
<p><input type="text" name="toDate" id="toDate" placeholder="yyyy-mm-dd" value="2000-03-01" /></p>
<p><input type="button" name="calculate" value="Calculate" onclick="javascript:calculate();" /></p>
<p />
<p id="result"></p>
let startDate = moment(new Date('2017-05-12')); // yyyy-MM-dd
let endDate = moment(new Date('2018-09-14')); // yyyy-MM-dd
let Years = newDate.diff(date, 'years');
let months = newDate.diff(date, 'months');
let days = newDate.diff(date, 'days');
console.log("Year: " + Years, ", Month: " months-(Years*12), ", Days: " days-(Years*365.25)-((365.25*(days- (Years*12)))/12));
Above snippet will print: Year: 1, Month: 4, Days: 2
Using Plane Javascript:
function dateDiffInDays(start, end) {
var MS_PER_DAY = 1000 * 60 * 60 * 24;
var a = new Date(start);
var b = new Date(end);
const diffTime = Math.abs(a - b);
const diffDays = Math.ceil(diffTime / MS_PER_DAY);
console.log("Days: ", diffDays);
// Discard the time and time-zone information.
const utc1 = Date.UTC(a.getFullYear(), a.getMonth(), a.getDate());
const utc2 = Date.UTC(b.getFullYear(), b.getMonth(), b.getDate());
return Math.floor((utc2 - utc1) / MS_PER_DAY);
}
function dateDiffInDays_Months_Years(start, end) {
var m1 = new Date(start);
var m2 = new Date(end);
var yDiff = m2.getFullYear() - m1.getFullYear();
var mDiff = m2.getMonth() - m1.getMonth();
var dDiff = m2.getDate() - m1.getDate();
if (dDiff < 0) {
var daysInLastFullMonth = getDaysInLastFullMonth(start);
if (daysInLastFullMonth < m1.getDate()) {
dDiff = daysInLastFullMonth + dDiff + (m1.getDate() -
daysInLastFullMonth);
} else {
dDiff = daysInLastFullMonth + dDiff;
}
mDiff--;
}
if (mDiff < 0) {
mDiff = 12 + mDiff;
yDiff--;
}
console.log('Y:', yDiff, ', M:', mDiff, ', D:', dDiff);
}
function getDaysInLastFullMonth(day) {
var d = new Date(day);
console.log(d.getDay() );
var lastDayOfMonth = new Date(d.getFullYear(), d.getMonth() + 1, 0);
console.log('last day of month:', lastDayOfMonth.getDate() ); //
return lastDayOfMonth.getDate();
}
Using moment.js:
function dateDiffUsingMoment(start, end) {
var a = moment(start,'M/D/YYYY');
var b = moment(end,'M/D/YYYY');
var diffDaysMoment = b.diff(a, 'days');
console.log('Moments.js : ', diffDaysMoment);
preciseDiffMoments(a,b);
}
function preciseDiffMoments( a, b) {
var m1= a, m2=b;
m1.add(m2.utcOffset() - m1.utcOffset(), 'minutes'); // shift timezone of m1 to m2
var yDiff = m2.year() - m1.year();
var mDiff = m2.month() - m1.month();
var dDiff = m2.date() - m1.date();
if (dDiff < 0) {
var daysInLastFullMonth = moment(m2.year() + '-' + (m2.month() + 1),
"YYYY-MM").subtract(1, 'M').daysInMonth();
if (daysInLastFullMonth < m1.date()) { // 31/01 -> 2/03
dDiff = daysInLastFullMonth + dDiff + (m1.date() -
daysInLastFullMonth);
} else {
dDiff = daysInLastFullMonth + dDiff;
}
mDiff--;
}
if (mDiff < 0) {
mDiff = 12 + mDiff;
yDiff--;
}
console.log('getMomentum() Y:', yDiff, ', M:', mDiff, ', D:', dDiff);
}
Tested the above functions using following samples:
var sample1 = all('2/13/2018', '3/15/2018'); // {'M/D/YYYY'} 30, Y: 0 , M: 1 , D: 2
console.log(sample1);
var sample2 = all('10/09/2019', '7/7/2020'); // 272, Y: 0 , M: 8 , D: 29
console.log(sample2);
function all(start, end) {
dateDiffInDays(start, end);
dateDiffInDays_Months_Years(start, end);
try {
dateDiffUsingMoment(start, end);
} catch (e) {
console.log(e);
}
}
by using Moment library and some custom logic, we can get the exact date difference
var out;
out = diffDate(new Date('2014-05-10'), new Date('2015-10-10'));
display(out);
out = diffDate(new Date('2014-05-10'), new Date('2015-10-09'));
display(out);
out = diffDate(new Date('2014-05-10'), new Date('2015-09-09'));
display(out);
out = diffDate(new Date('2014-05-10'), new Date('2015-03-09'));
display(out);
out = diffDate(new Date('2014-05-10'), new Date('2016-03-09'));
display(out);
out = diffDate(new Date('2014-05-10'), new Date('2016-03-11'));
display(out);
function diffDate(startDate, endDate) {
var b = moment(startDate),
a = moment(endDate),
intervals = ['years', 'months', 'weeks', 'days'],
out = {};
for (var i = 0; i < intervals.length; i++) {
var diff = a.diff(b, intervals[i]);
b.add(diff, intervals[i]);
out[intervals[i]] = diff;
}
return out;
}
function display(obj) {
var str = '';
for (key in obj) {
str = str + obj[key] + ' ' + key + ' '
}
console.log(str);
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.24.0/moment.js"></script>
I did it using a bunch of functions. Pure JavaScript and precise.
This code includes functions that calculate time difference in days, months and years. One of them can be used to get precise time difference for example X years, Y months, Z days. At the end of code I provided some tests.
How it works:
getDaysDiff():
Transforms time difference from milliseconds to days.
getYearsDiff():
There is no worries for effect of months and days of both dates. The function calculates difference in years by moving dates back and forward.
getMonthsDiff() (This one has nothing to do with question, but the concept is used in calExactTimeDiff() and I thought someone may need such a function so I insert it):
This one is a little tricky. The hard work is to deal with month and day of both dates.
If the endDate's month is more than startDate's, this means another year (12 months) is passed. But this is being taken care of in monthsOfFullYears, so the only thing is needed is to add subtraction of month of endDate and startDate.
If the startDate's month is more than endDate's then there is no another year. So we should get the difference between them. Imagine we want to go from month 10 of the current year to 2 of the next year. We can go like this: 11, 12, 1, 2. So we passed 4 months. This is equal to 12 - (10 - 2). We get difference between the months and subtract it from months of a whole year.
Next step is to take care of days of months. If day of endDate is more than or equal to startDate this means another month is passed. So we add 1 to it. But if it's less, then there is nothing to worry about. But in my code I did not do this. Because when I added difference between months I assumed that the days of months are equal. So I already added 1. Thus if day of endDate is less than startDate, I have to decrease months by 1.
There is an exception: if months are equal and endDate's day is less than startDate's, month should be 11.
I used the same concept in calExactTimeDiff().
Hope to be useful :)
// time difference in Days
function getDaysDiff(startDate = new Date(), endDate = new Date()) {
if (startDate > endDate) [startDate, endDate] = [endDate, startDate];
let timeDiff = endDate - startDate;
let timeDiffInDays = Math.floor(timeDiff / (1000 * 3600 * 24));
return timeDiffInDays;
}
// time difference in Months
function getMonthsDiff(startDate = new Date(), endDate = new Date()) {
let monthsOfFullYears = getYearsDiff(startDate, endDate) * 12;
let months = monthsOfFullYears;
// the variable below is not necessary, but I kept it for understanding of code
// we can use "startDate" instead of it
let yearsAfterStart = new Date(
startDate.getFullYear() + getYearsDiff(startDate, endDate),
startDate.getMonth(),
startDate.getDate()
);
let isDayAhead = endDate.getDate() >= yearsAfterStart.getDate();
if (startDate.getMonth() == endDate.getMonth() && !isDayAhead) {
months = 11;
return months;
}
if (endDate.getMonth() >= yearsAfterStart.getMonth()) {
let diff = endDate.getMonth() - yearsAfterStart.getMonth();
months += (isDayAhead) ? diff : diff - 1;
}
else {
months += isDayAhead
? 12 - (startDate.getMonth() - endDate.getMonth())
: 12 - (startDate.getMonth() - endDate.getMonth()) - 1;
}
return months;
}
// time difference in Years
function getYearsDiff(startDate = new Date(), endDate = new Date()) {
if (startDate > endDate) [startDate, endDate] = [endDate, startDate];
let yearB4End = new Date(
endDate.getFullYear() - 1,
endDate.getMonth(),
endDate.getDate()
);
let year = 0;
year = yearB4End > startDate
? yearB4End.getFullYear() - startDate.getFullYear()
: 0;
let yearsAfterStart = new Date(
startDate.getFullYear() + year + 1,
startDate.getMonth(),
startDate.getDate()
);
if (endDate >= yearsAfterStart) year++;
return year;
}
// time difference in format: X years, Y months, Z days
function calExactTimeDiff(firstDate, secondDate) {
if (firstDate > secondDate)
[firstDate, secondDate] = [secondDate, firstDate];
let monthDiff = 0;
let isDayAhead = secondDate.getDate() >= firstDate.getDate();
if (secondDate.getMonth() >= firstDate.getMonth()) {
let diff = secondDate.getMonth() - firstDate.getMonth();
monthDiff += (isDayAhead) ? diff : diff - 1;
}
else {
monthDiff += isDayAhead
? 12 - (firstDate.getMonth() - secondDate.getMonth())
: 12 - (firstDate.getMonth() - secondDate.getMonth()) - 1;
}
let dayDiff = 0;
if (isDayAhead) {
dayDiff = secondDate.getDate() - firstDate.getDate();
}
else {
let b4EndDate = new Date(
secondDate.getFullYear(),
secondDate.getMonth() - 1,
firstDate.getDate()
)
dayDiff = getDaysDiff(b4EndDate, secondDate);
}
if (firstDate.getMonth() == secondDate.getMonth() && !isDayAhead)
monthDiff = 11;
let exactTimeDiffUnits = {
yrs: getYearsDiff(firstDate, secondDate),
mths: monthDiff,
dys: dayDiff,
};
return `${exactTimeDiffUnits.yrs} years, ${exactTimeDiffUnits.mths} months, ${exactTimeDiffUnits.dys} days`
}
let s = new Date(2012, 4, 12);
let e = new Date(2008, 5, 24);
console.log(calExactTimeDiff(s, e));
s = new Date(2001, 7, 4);
e = new Date(2016, 6, 9);
console.log(calExactTimeDiff(s, e));
s = new Date(2011, 11, 28);
e = new Date(2021, 3, 6);
console.log(calExactTimeDiff(s, e));
s = new Date(2020, 8, 7);
e = new Date(2021, 8, 6);
console.log(calExactTimeDiff(s, e));
There a a couple of npm packages that help in doing this. Below is a list gathered from various sources. I find the date-fns version to be the most simplest.
1. date-fns
You can use intervalToDuration, formatDuration from date-fns to humanize a duration in desired format like below:
import { intervalToDuration, formatDuration } from 'date-fns'
let totalDuration = intervalToDuration({
start: new Date(1929, 0, 15, 12, 0, 0),
end: new Date(1968, 3, 4, 19, 5, 0)
});
let textDuration = formatDuration(totalDuration, { format: ['years', 'months'], delimiter: ', ' })
// Output: "39 years, 2 months"
clone the above code from here for trying it yourself: https://runkit.com/embed/diu9o3qe53j4
2. luxon + humanize-duration
you can use luxon to extract the duration between dates and humanize that using humanize-duration like below:
const DateTime = luxon.DateTime;
const Interval = luxon.Interval;
const start = DateTime.fromSQL("2020-06-19 11:14:00");
const finish = DateTime.fromSQL("2020-06-21 13:11:00");
const formatted = Interval
.fromDateTimes(start, finish)
.toDuration()
.valueOf();
console.log(humanizeDuration(formatted))
// output: 2 days, 1 hour, 57 minutes
console.log(humanizeDuration(formatted, { language: 'es' }))
// output: 2 días, 1 hora, 57 minutos
console.log(humanizeDuration(formatted, { language: 'ru' }))
// output: 2 дня, 1 час, 57 минут
<script src="https://cdn.jsdelivr.net/npm/luxon#1.25.0/build/global/luxon.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/humanize-duration#3.25.1/humanize-duration.min.js"></script>
reference to above code: https://stackoverflow.com/a/65651515/6908282
I would personally use http://www.datejs.com/, really handy. Specifically, look at the time.js file: http://code.google.com/p/datejs/source/browse/trunk/src/time.js
Time span in full Days, Hours, Minutes, Seconds, Milliseconds:
// Extension for Date
Date.difference = function (dateFrom, dateTo) {
var diff = { TotalMs: dateTo - dateFrom };
diff.Days = Math.floor(diff.TotalMs / 86400000);
var remHrs = diff.TotalMs % 86400000;
var remMin = remHrs % 3600000;
var remS = remMin % 60000;
diff.Hours = Math.floor(remHrs / 3600000);
diff.Minutes = Math.floor(remMin / 60000);
diff.Seconds = Math.floor(remS / 1000);
diff.Milliseconds = Math.floor(remS % 1000);
return diff;
};
// Usage
var a = new Date(2014, 05, 12, 00, 5, 45, 30); //a: Thu Jun 12 2014 00:05:45 GMT+0400
var b = new Date(2014, 02, 12, 00, 0, 25, 0); //b: Wed Mar 12 2014 00:00:25 GMT+0400
var diff = Date.difference(b, a);
/* diff: {
Days: 92
Hours: 0
Minutes: 5
Seconds: 20
Milliseconds: 30
TotalMs: 7949120030
} */
Neither of the codes work for me, so I use this instead for months and days:
function monthDiff(d2, d1) {
var months;
months = (d2.getFullYear() - d1.getFullYear()) * 12;
months -= d1.getMonth() + 1;
months += d2.getMonth() + 1;
return months <= 0 ? 0 : months;
}
function daysInMonth(date) {
return new Date(date.getYear(), date.getMonth() + 1, 0).getDate();
}
function diffDate(date1, date2) {
if (date2 && date2.getTime() && !isNaN(date2.getTime())) {
var months = monthDiff(date1, date2);
var days = 0;
if (date1.getUTCDate() >= date2.getUTCDate()) {
days = date1.getUTCDate() - date2.getUTCDate();
}
else {
months--;
days = date1.getUTCDate() - date2.getUTCDate() + daysInMonth(date2);
}
// Use the variables months and days how you need them.
}
}
The following is an algorithm which gives correct but not totally precise since it does not take into account leap year. It also assumes 30 days in a month. A good usage for example is if someone lives in an address from 12/11/2010 to 11/10/2011, it can quickly tells that the person lives there for 10 months and 29 days. From 12/11/2010 to 11/12/2011 is 11 months and 1 day. For certain types of applications, that kind of precision is sufficient. This is for those types of applications because it aims for simplicity:
var datediff = function(start, end) {
var diff = { years: 0, months: 0, days: 0 };
var timeDiff = end - start;
if (timeDiff > 0) {
diff.years = end.getFullYear() - start.getFullYear();
diff.months = end.getMonth() - start.getMonth();
diff.days = end.getDate() - start.getDate();
if (diff.months < 0) {
diff.years--;
diff.months += 12;
}
if (diff.days < 0) {
diff.months = Math.max(0, diff.months - 1);
diff.days += 30;
}
}
return diff;
};
Unit tests
To calculate the difference between two dates in Years, Months, Days, Minutes, Seconds, Milliseconds using TypeScript/ JavaScript
dateDifference(actualDate) {
// Calculate time between two dates:
const date1 = actualDate; // the date you already commented/ posted
const date2: any = new Date(); // today
let r = {}; // object for clarity
let message: string;
const diffInSeconds = Math.abs(date2 - date1) / 1000;
const days = Math.floor(diffInSeconds / 60 / 60 / 24);
const hours = Math.floor(diffInSeconds / 60 / 60 % 24);
const minutes = Math.floor(diffInSeconds / 60 % 60);
const seconds = Math.floor(diffInSeconds % 60);
const milliseconds =
Math.round((diffInSeconds - Math.floor(diffInSeconds)) * 1000);
const months = Math.floor(days / 31);
const years = Math.floor(months / 12);
// the below object is just optional
// if you want to return an object instead of a message
r = {
years: years,
months: months,
days: days,
hours: hours,
minutes: minutes,
seconds: seconds,
milliseconds: milliseconds
};
// check if difference is in years or months
if (years === 0 && months === 0) {
// show in days if no years / months
if (days > 0) {
if (days === 1) {
message = days + ' day';
} else { message = days + ' days'; }
} else if (hours > 0) {
if (hours === 1) {
message = hours + ' hour';
} else {
message = hours + ' hours';
}
} else {
// show in minutes if no years / months / days
if (minutes === 1) {
message = minutes + ' minute';
} else {message = minutes + ' minutes';}
}
} else if (years === 0 && months > 0) {
// show in months if no years
if (months === 1) {
message = months + ' month';
} else {message = months + ' months';}
} else if (years > 0) {
// show in years if years exist
if (years === 1) {
message = years + ' year';
} else {message = years + ' years';}
}
return 'Posted ' + message + ' ago';
// this is the message a user see in the view
}
However, you can update the above logic for the message to show seconds and milliseconds too or else use the object 'r' to format the message whatever way you want.
If you want to directly copy the code, you can view my gist with the above code here
I know it is an old thread, but I'd like to put my 2 cents based on the answer by #Pawel Miech.
It is true that you need to convert the difference into milliseconds, then you need to make some math. But notice that, you need to do the math in backward manner, i.e. you need to calculate years, months, days, hours then minutes.
I used to do some thing like this:
var mins;
var hours;
var days;
var months;
var years;
var diff = new Date() - new Date(yourOldDate);
// yourOldDate may be is coming from DB, for example, but it should be in the correct format ("MM/dd/yyyy hh:mm:ss:fff tt")
years = Math.floor((diff) / (1000 * 60 * 60 * 24 * 365));
diff = Math.floor((diff) % (1000 * 60 * 60 * 24 * 365));
months = Math.floor((diff) / (1000 * 60 * 60 * 24 * 30));
diff = Math.floor((diff) % (1000 * 60 * 60 * 24 * 30));
days = Math.floor((diff) / (1000 * 60 * 60 * 24));
diff = Math.floor((diff) % (1000 * 60 * 60 * 24));
hours = Math.floor((diff) / (1000 * 60 * 60));
diff = Math.floor((diff) % (1000 * 60 * 60));
mins = Math.floor((diff) / (1000 * 60));
But, of course, this is not precise because it assumes that all years have 365 days and all months have 30 days, which is not true in all cases.
Its very simple please use the code below and it will give the difference in that format according to this //3 years 9 months 3 weeks 5 days 15 hours 50 minutes
Date.getFormattedDateDiff = function(date1, date2) {
var b = moment(date1),
a = moment(date2),
intervals = ['years','months','weeks','days'],
out = [];
for(var i=0; i<intervals.length; i++){
var diff = a.diff(b, intervals[i]);
b.add(diff, intervals[i]);
out.push(diff + ' ' + intervals[i]);
}
return out.join(', ');
};
var today = new Date(),
newYear = new Date(today.getFullYear(), 0, 1),
y2k = new Date(2000, 0, 1);
//(AS OF NOV 29, 2016)
//Time since New Year: 0 years, 10 months, 4 weeks, 0 days
console.log( 'Time since New Year: ' + Date.getFormattedDateDiff(newYear, today) );
//Time since Y2K: 16 years, 10 months, 4 weeks, 0 days
console.log( 'Time since Y2K: ' + Date.getFormattedDateDiff(y2k, today) );
This code should give you desired results
//************************** Enter your dates here **********************//
var startDate = "10/05/2014";
var endDate = "11/3/2016"
//******* and press "Run", you will see the result in a popup *********//
var noofdays = 0;
var sdArr = startDate.split("/");
var startDateDay = parseInt(sdArr[0]);
var startDateMonth = parseInt(sdArr[1]);
var startDateYear = parseInt(sdArr[2]);
sdArr = endDate.split("/")
var endDateDay = parseInt(sdArr[0]);
var endDateMonth = parseInt(sdArr[1]);
var endDateYear = parseInt(sdArr[2]);
console.log(startDateDay+' '+startDateMonth+' '+startDateYear);
var yeardays = 365;
var monthArr = [31,,31,30,31,30,31,31,30,31,30,31];
var noofyears = 0
var noofmonths = 0;
if((startDateYear%4)==0) monthArr[1]=29;
else monthArr[1]=28;
if(startDateYear == endDateYear){
noofyears = 0;
noofmonths = getMonthDiff(startDate,endDate);
if(noofmonths < 0) noofmonths = 0;
noofdays = getDayDiff(startDate,endDate);
}else{
if(endDateMonth < startDateMonth){
noofyears = (endDateYear - startDateYear)-1;
if(noofyears < 1) noofyears = 0;
}else{
noofyears = endDateYear - startDateYear;
}
noofmonths = getMonthDiff(startDate,endDate);
if(noofmonths < 0) noofmonths = 0;
noofdays = getDayDiff(startDate,endDate);
}
alert(noofyears+' year, '+ noofmonths+' months, '+ noofdays+' days');
function getDayDiff(startDate,endDate){
if(endDateDay >=startDateDay){
noofdays = 0;
if(endDateDay > startDateDay) {
noofdays = endDateDay - startDateDay;
}
}else{
if((endDateYear%4)==0) {
monthArr[1]=29;
}else{
monthArr[1] = 28;
}
if(endDateMonth != 1)
noofdays = (monthArr[endDateMonth-2]-startDateDay) + endDateDay;
else
noofdays = (monthArr[11]-startDateDay) + endDateDay;
}
return noofdays;
}
function getMonthDiff(startDate,endDate){
if(endDateMonth > startDateMonth){
noofmonths = endDateMonth - startDateMonth;
if(endDateDay < startDateDay){
noofmonths--;
}
}else{
noofmonths = (12-startDateMonth) + endDateMonth;
if(endDateDay < startDateDay){
noofmonths--;
}
}
return noofmonths;
}
https://jsfiddle.net/moremanishk/hk8c419f/
You should try using date-fns. Here's how I did it using intervalToDuration and formatDuration functions from date-fns.
let startDate = Date.parse("2010-10-01 00:00:00 UTC");
let endDate = Date.parse("2020-11-01 00:00:00 UTC");
let duration = intervalToDuration({start: startDate, end: endDate});
let durationInWords = formatDuration(duration, {format: ["years", "months", "days"]}); //output: 10 years 1 month
since I had to use moment-hijri (hijri calendar) and couldn't use moment.diff() method, I came up with this solution. can also be used with moment.js
var momenti = require('moment-hijri')
//calculate hijri
var strt = await momenti(somedateobject)
var until = await momenti()
var years = await 0
var months = await 0
var days = await 0
while(strt.valueOf() < until.valueOf()){
await strt.add(1, 'iYear');
await years++
}
await strt.subtract(1, 'iYear');
await years--
while(strt.valueOf() < until.valueOf()){
await strt.add(1, 'iMonth');
await months++
}
await strt.subtract(1, 'iMonth');
await months--
while(strt.valueOf() < until.valueOf()){
await strt.add(1, 'day');
await days++
}
await strt.subtract(1, 'day');
await days--
await console.log(years)
await console.log(months)
await console.log(days)
A solution with the ECMAScript "Temporal API" which is currently (as of 5th March 2022) in Stage 3 of Active Proposals, which will the method we will do this in the future (soon).
Here is a solution with the current temporal-polyfill
<script type='module'>
import * as TemporalModule from 'https://cdn.jsdelivr.net/npm/#js-temporal/polyfill#0.3.0/dist/index.umd.js'
const Temporal = temporal.Temporal;
//----------------------------------------
function dateDiff(start, end, maxUnit) {
return (Temporal.PlainDate.from(start).until(Temporal.PlainDate.from(end),{largestUnit:maxUnit}).toString()).match(/(\d*Y)|(\d*M)|(\d*D)/g).join(" ");
}
//----------------------------------------
console.log("Diff in (years, months, days): ",dateDiff("1963-02-03","2022-03-06","year"))
console.log("Diff in (months, days) : ",dateDiff("1963-02-03","2022-03-06","month"))
console.log("Diff in (days) : ",dateDiff("1963-02-03","2022-03-06","day"))
</script>
Your expected output is not correct. For example difference between '2014-05-10' and '2015-03-09' is not 9 months, 27 days
the correct answer is
(05-10 to 05-31) = 21 days
(2014-06 to 2015-03) = 9 months
(03-01 to 03-09) = 9 days
total is 9 months and 30 days
WARNING: An ideal function would be aware of leap years and days count in every month, but I found the results of this function accurate enough for my current task, so I shared it with you
function diffDate(date1, date2)
{
var daysDiff = Math.ceil((Math.abs(date1 - date2)) / (1000 * 60 * 60 * 24));
var years = Math.floor(daysDiff / 365.25);
var remainingDays = Math.floor(daysDiff - (years * 365.25));
var months = Math.floor((remainingDays / 365.25) * 12);
var days = Math.ceil(daysDiff - (years * 365.25 + (months / 12 * 365.25)));
return {
daysAll: daysDiff,
years: years,
months: months,
days:days
}
}
console.log(diffDate(new Date('2014-05-10'), new Date('2015-10-10')));
console.log(diffDate(new Date('2014-05-10'), new Date('2015-10-09')));
console.log(diffDate(new Date('2014-05-10'), new Date('2015-09-09')));
console.log(diffDate(new Date('2014-05-10'), new Date('2015-03-09')));
console.log(diffDate(new Date('2014-05-10'), new Date('2016-03-09')));
console.log(diffDate(new Date('2014-05-10'), new Date('2016-03-11')));

Is it possible to determine age, in one of the standard Day/Month/Year formats (NOT MS), using 2 Date objects? [duplicate]

How to get the difference between two dates in years, months, and days in JavaScript, like: 10th of April 2010 was 3 years, x month and y days ago?
There are lots of solutions, but they only offer the difference in the format of either days OR months OR years, or they are not correct (meaning not taking care of actual number of days in a month or leap years, etc). Is it really that difficult to do that?
I've had a look at:
http://momentjs.com/ -> can only output the difference in either years, months, OR days
http://www.javascriptkit.com/javatutors/datedifference.shtml
http://www.javascriptkit.com/jsref/date.shtml
http://timeago.yarp.com/
www.stackoverflow.com -> Search function
In php it is easy, but unfortunately I can only use client-side script on that project. Any library or framework that can do it would be fine, too.
Here are a list of expected outputs for date differences:
//Expected output should be: "1 year, 5 months".
diffDate(new Date('2014-05-10'), new Date('2015-10-10'));
//Expected output should be: "1 year, 4 months, 29 days".
diffDate(new Date('2014-05-10'), new Date('2015-10-09'));
//Expected output should be: "1 year, 3 months, 30 days".
diffDate(new Date('2014-05-10'), new Date('2015-09-09'));
//Expected output should be: "9 months, 27 days".
diffDate(new Date('2014-05-10'), new Date('2015-03-09'));
//Expected output should be: "1 year, 9 months, 28 days".
diffDate(new Date('2014-05-10'), new Date('2016-03-09'));
//Expected output should be: "1 year, 10 months, 1 days".
diffDate(new Date('2014-05-10'), new Date('2016-03-11'));
How precise do you need to be? If you do need to take into account common years and leap years, and the exact difference in days between months then you'll have to write something more advanced but for a basic and rough calculation this should do the trick:
today = new Date()
past = new Date(2010,05,01) // remember this is equivalent to 06 01 2010
//dates in js are counted from 0, so 05 is june
function calcDate(date1,date2) {
var diff = Math.floor(date1.getTime() - date2.getTime());
var day = 1000 * 60 * 60 * 24;
var days = Math.floor(diff/day);
var months = Math.floor(days/31);
var years = Math.floor(months/12);
var message = date2.toDateString();
message += " was "
message += days + " days "
message += months + " months "
message += years + " years ago \n"
return message
}
a = calcDate(today,past)
console.log(a) // returns Tue Jun 01 2010 was 1143 days 36 months 3 years ago
Keep in mind that this is imprecise, in order to calculate the date with full precision one would have to have a calendar and know if a year is a leap year or not, also the way I'm calculating the number of months is only approximate.
But you can improve it easily.
Actually, there's a solution with a moment.js plugin and it's very easy.
You might use moment.js
Don't reinvent the wheel again.
Just plug Moment.js Date Range Plugin.
Example:
var starts = moment('2014-02-03 12:53:12');
var ends = moment();
var duration = moment.duration(ends.diff(starts));
// with ###moment precise date range plugin###
// it will tell you the difference in human terms
var diff = moment.preciseDiff(starts, ends, true);
// example: { "years": 2, "months": 7, "days": 0, "hours": 6, "minutes": 29, "seconds": 17, "firstDateWasLater": false }
// or as string:
var diffHuman = moment.preciseDiff(starts, ends);
// example: 2 years 7 months 6 hours 29 minutes 17 seconds
document.getElementById('output1').innerHTML = JSON.stringify(diff)
document.getElementById('output2').innerHTML = diffHuman
<html>
<head>
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.14.1/moment.min.js"></script>
<script src="https://raw.githubusercontent.com/codebox/moment-precise-range/master/moment-precise-range.js"></script>
</head>
<body>
<h2>Difference between "NOW and 2014-02-03 12:53:12"</h2>
<span id="output1"></span>
<br />
<span id="output2"></span>
</body>
</html>
Modified this to be a lot more accurate. It will convert dates to a 'YYYY-MM-DD' format, ignoring HH:MM:SS, and takes an optional endDate or uses the current date, and doesn't care about the order of the values.
function dateDiff(startingDate, endingDate) {
let startDate = new Date(new Date(startingDate).toISOString().substr(0, 10));
if (!endingDate) {
endingDate = new Date().toISOString().substr(0, 10); // need date in YYYY-MM-DD format
}
let endDate = new Date(endingDate);
if (startDate > endDate) {
const swap = startDate;
startDate = endDate;
endDate = swap;
}
const startYear = startDate.getFullYear();
const february = (startYear % 4 === 0 && startYear % 100 !== 0) || startYear % 400 === 0 ? 29 : 28;
const daysInMonth = [31, february, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31];
let yearDiff = endDate.getFullYear() - startYear;
let monthDiff = endDate.getMonth() - startDate.getMonth();
if (monthDiff < 0) {
yearDiff--;
monthDiff += 12;
}
let dayDiff = endDate.getDate() - startDate.getDate();
if (dayDiff < 0) {
if (monthDiff > 0) {
monthDiff--;
} else {
yearDiff--;
monthDiff = 11;
}
dayDiff += daysInMonth[startDate.getMonth()];
}
return yearDiff + 'Y ' + monthDiff + 'M ' + dayDiff + 'D';
}
// Examples
let dates = [
['2019-05-10','2019-05-10'], // 0Y 0M 0D
['2019-05-09','2019-05-10'], // 0Y 0M 1D
['2018-05-09','2019-05-10'], // 1Y 0M 1D
['2018-05-18','2019-05-10'], // 0Y 11M 23D
['2019-01-09','2019-05-10'], // 0Y 4M 1D
['2019-02-10','2019-05-10'], // 0Y 3M 0D
['2019-02-11','2019-05-10'], // 0Y 2M 27D
['2016-02-11','2019-05-10'], // 3Y 2M 28D - leap year
['1972-11-30','2019-05-10'], // 46Y 5M 10D
['2016-02-11','2017-02-11'], // 1Y 0M 0D
['2016-02-11','2016-03-10'], // 0Y 0M 28D - leap year
['2100-02-11','2100-03-10'], // 0Y 0M 27D - not a leap year
['2017-02-11','2016-02-11'], // 1Y 0M 0D - swapped dates to return correct result
[new Date() - 1000 * 60 * 60 * 24] // 0Y 0M 1D - uses current date
].forEach(([s, e]) => console.log(dateDiff(s, e)));
Older less accurate but much simpler version
#RajeevPNadig's answer was what I was looking for, but his code returns incorrect values as written. This code is not very accurate because it assumes that the sequence of dates from 1 January 1970 is the same as any other sequence of the same number of days. E.g. it calculates the difference from 1 July to 1 September (62 days) as 0Y 2M 3D and not 0Y 2M 0D because 1 Jan 1970 plus 62 days is 3 March.
// startDate must be a date string
function dateAgo(date) {
var startDate = new Date(date);
var diffDate = new Date(new Date() - startDate);
return ((diffDate.toISOString().slice(0, 4) - 1970) + "Y " +
diffDate.getMonth() + "M " + (diffDate.getDate()-1) + "D");
}
Then you can use it like this:
// based on a current date of 2018-03-09
dateAgo('1972-11-30'); // "45Y 3M 9D"
dateAgo('2017-03-09'); // "1Y 0M 0D"
dateAgo('2018-01-09'); // "0Y 2M 0D"
dateAgo('2018-02-09'); // "0Y 0M 28D" -- a little odd, but not wrong
dateAgo('2018-02-01'); // "0Y 1M 5D" -- definitely "feels" wrong
dateAgo('2018-03-09'); // "0Y 0M 0D"
If your use case is just date strings, then this works okay if you just want a quick and dirty 4 liner.
I used this simple code to get difference in Years, Months, days with current date.
var sdt = new Date('1972-11-30');
var difdt = new Date(new Date() - sdt);
alert((difdt.toISOString().slice(0, 4) - 1970) + "Y " + (difdt.getMonth()+1) + "M " + difdt.getDate() + "D");
I think you are looking for the same thing that I wanted. I tried to do this using the difference in milliseconds that javascript provides, but those results do not work in the real world of dates. If you want the difference between Feb 1, 2016 and January 31, 2017 the result I would want is 1 year, 0 months, and 0 days. Exactly one year (assuming you count the last day as a full day, like in a lease for an apartment). However, the millisecond approach would give you 1 year 0 months and 1 day, since the date range includes a leap year. So here is the code I used in javascript for my adobe form (you can name the fields): (edited, there was an error that I corrected)
var f1 = this.getField("LeaseExpiration");
var g1 = this.getField("LeaseStart");
var end = f1.value
var begin = g1.value
var e = new Date(end);
var b = new Date(begin);
var bMonth = b.getMonth();
var bYear = b.getFullYear();
var eYear = e.getFullYear();
var eMonth = e.getMonth();
var bDay = b.getDate();
var eDay = e.getDate() + 1;
if ((eMonth == 0)||(eMonth == 2)||(eMonth == 4)|| (eMonth == 6) || (eMonth == 7) ||(eMonth == 9)||(eMonth == 11))
{
var eDays = 31;
}
if ((eMonth == 3)||(eMonth == 5)||(eMonth == 8)|| (eMonth == 10))
{
var eDays = 30;
}
if (eMonth == 1&&((eYear % 4 == 0) && (eYear % 100 != 0)) || (eYear % 400 == 0))
{
var eDays = 29;
}
if (eMonth == 1&&((eYear % 4 != 0) || (eYear % 100 == 0)))
{
var eDays = 28;
}
if ((bMonth == 0)||(bMonth == 2)||(bMonth == 4)|| (bMonth == 6) || (bMonth == 7) ||(bMonth == 9)||(bMonth == 11))
{
var bDays = 31;
}
if ((bMonth == 3)||(bMonth == 5)||(bMonth == 8)|| (bMonth == 10))
{
var bDays = 30;
}
if (bMonth == 1&&((bYear % 4 == 0) && (bYear % 100 != 0)) || (bYear % 400 == 0))
{
var bDays = 29;
}
if (bMonth == 1&&((bYear % 4 != 0) || (bYear % 100 == 0)))
{
var bDays = 28;
}
var FirstMonthDiff = bDays - bDay + 1;
if (eDay - bDay < 0)
{
eMonth = eMonth - 1;
eDay = eDay + eDays;
}
var daysDiff = eDay - bDay;
if(eMonth - bMonth < 0)
{
eYear = eYear - 1;
eMonth = eMonth + 12;
}
var monthDiff = eMonth - bMonth;
var yearDiff = eYear - bYear;
if (daysDiff == eDays)
{
daysDiff = 0;
monthDiff = monthDiff + 1;
if (monthDiff == 12)
{
monthDiff = 0;
yearDiff = yearDiff + 1;
}
}
if ((FirstMonthDiff != bDays)&&(eDay - 1 == eDays))
{
daysDiff = FirstMonthDiff;
}
event.value = yearDiff + " Year(s)" + " " + monthDiff + " month(s) " + daysDiff + " days(s)"
I have created, yet another one, function for this purpose:
function dateDiff(date) {
date = date.split('-');
var today = new Date();
var year = today.getFullYear();
var month = today.getMonth() + 1;
var day = today.getDate();
var yy = parseInt(date[0]);
var mm = parseInt(date[1]);
var dd = parseInt(date[2]);
var years, months, days;
// months
months = month - mm;
if (day < dd) {
months = months - 1;
}
// years
years = year - yy;
if (month * 100 + day < mm * 100 + dd) {
years = years - 1;
months = months + 12;
}
// days
days = Math.floor((today.getTime() - (new Date(yy + years, mm + months - 1, dd)).getTime()) / (24 * 60 * 60 * 1000));
//
return {years: years, months: months, days: days};
}
Doesn't require any 3rd party libraries. Takes one argument -- date in YYYY-MM-DD format.
https://gist.github.com/lemmon/d27c2d4a783b1cf72d1d1cc243458d56
With dayjs we did it in that way:
export const getAgeDetails = (oldDate: dayjs.Dayjs, newDate: dayjs.Dayjs) => {
const years = newDate.diff(oldDate, 'year');
const months = newDate.diff(oldDate, 'month') - years * 12;
const days = newDate.diff(oldDate.add(years, 'year').add(months, 'month'), 'day');
return {
years,
months,
days,
allDays: newDate.diff(oldDate, 'day'),
};
};
It calculates it perfectly including leap years and different month amount of days.
For quick and easy use I wrote this function some time ago. It returns the diff between two dates in a nice format. Feel free to use it (tested on webkit).
/**
* Function to print date diffs.
*
* #param {Date} fromDate: The valid start date
* #param {Date} toDate: The end date. Can be null (if so the function uses "now").
* #param {Number} levels: The number of details you want to get out (1="in 2 Months",2="in 2 Months, 20 Days",...)
* #param {Boolean} prefix: adds "in" or "ago" to the return string
* #return {String} Diffrence between the two dates.
*/
function getNiceTime(fromDate, toDate, levels, prefix){
var lang = {
"date.past": "{0} ago",
"date.future": "in {0}",
"date.now": "now",
"date.year": "{0} year",
"date.years": "{0} years",
"date.years.prefixed": "{0} years",
"date.month": "{0} month",
"date.months": "{0} months",
"date.months.prefixed": "{0} months",
"date.day": "{0} day",
"date.days": "{0} days",
"date.days.prefixed": "{0} days",
"date.hour": "{0} hour",
"date.hours": "{0} hours",
"date.hours.prefixed": "{0} hours",
"date.minute": "{0} minute",
"date.minutes": "{0} minutes",
"date.minutes.prefixed": "{0} minutes",
"date.second": "{0} second",
"date.seconds": "{0} seconds",
"date.seconds.prefixed": "{0} seconds",
},
langFn = function(id,params){
var returnValue = lang[id] || "";
if(params){
for(var i=0;i<params.length;i++){
returnValue = returnValue.replace("{"+i+"}",params[i]);
}
}
return returnValue;
},
toDate = toDate ? toDate : new Date(),
diff = fromDate - toDate,
past = diff < 0 ? true : false,
diff = diff < 0 ? diff * -1 : diff,
date = new Date(new Date(1970,0,1,0).getTime()+diff),
returnString = '',
count = 0,
years = (date.getFullYear() - 1970);
if(years > 0){
var langSingle = "date.year" + (prefix ? "" : ""),
langMultiple = "date.years" + (prefix ? ".prefixed" : "");
returnString += (count > 0 ? ', ' : '') + (years > 1 ? langFn(langMultiple,[years]) : langFn(langSingle,[years]));
count ++;
}
var months = date.getMonth();
if(count < levels && months > 0){
var langSingle = "date.month" + (prefix ? "" : ""),
langMultiple = "date.months" + (prefix ? ".prefixed" : "");
returnString += (count > 0 ? ', ' : '') + (months > 1 ? langFn(langMultiple,[months]) : langFn(langSingle,[months]));
count ++;
} else {
if(count > 0)
count = 99;
}
var days = date.getDate() - 1;
if(count < levels && days > 0){
var langSingle = "date.day" + (prefix ? "" : ""),
langMultiple = "date.days" + (prefix ? ".prefixed" : "");
returnString += (count > 0 ? ', ' : '') + (days > 1 ? langFn(langMultiple,[days]) : langFn(langSingle,[days]));
count ++;
} else {
if(count > 0)
count = 99;
}
var hours = date.getHours();
if(count < levels && hours > 0){
var langSingle = "date.hour" + (prefix ? "" : ""),
langMultiple = "date.hours" + (prefix ? ".prefixed" : "");
returnString += (count > 0 ? ', ' : '') + (hours > 1 ? langFn(langMultiple,[hours]) : langFn(langSingle,[hours]));
count ++;
} else {
if(count > 0)
count = 99;
}
var minutes = date.getMinutes();
if(count < levels && minutes > 0){
var langSingle = "date.minute" + (prefix ? "" : ""),
langMultiple = "date.minutes" + (prefix ? ".prefixed" : "");
returnString += (count > 0 ? ', ' : '') + (minutes > 1 ? langFn(langMultiple,[minutes]) : langFn(langSingle,[minutes]));
count ++;
} else {
if(count > 0)
count = 99;
}
var seconds = date.getSeconds();
if(count < levels && seconds > 0){
var langSingle = "date.second" + (prefix ? "" : ""),
langMultiple = "date.seconds" + (prefix ? ".prefixed" : "");
returnString += (count > 0 ? ', ' : '') + (seconds > 1 ? langFn(langMultiple,[seconds]) : langFn(langSingle,[seconds]));
count ++;
} else {
if(count > 0)
count = 99;
}
if(prefix){
if(returnString == ""){
returnString = langFn("date.now");
} else if(past)
returnString = langFn("date.past",[returnString]);
else
returnString = langFn("date.future",[returnString]);
}
return returnString;
}
If you are using date-fns and if you dont want to install the Moment.js or the moment-precise-range-plugin. You can use the following date-fns function to get the same result as moment-precise-range-plugin
intervalToDuration({
start: new Date(),
end: new Date("24 Jun 2020")
})
This will give output in a JSON object like below
{
"years": 0,
"months": 0,
"days": 0,
"hours": 19,
"minutes": 35,
"seconds": 24
}
Live Example https://stackblitz.com/edit/react-wvxvql
Link to Documentation https://date-fns.org/v2.14.0/docs/intervalToDuration
Some math is in order.
You can subtract one Date object from another in Javascript, and you'll get the difference between them in milisseconds. From this result you can extract the other parts you want (days, months etc.)
For example:
var a = new Date(2010, 10, 1);
var b = new Date(2010, 9, 1);
var c = a - b; // c equals 2674800000,
// the amount of milisseconds between September 1, 2010
// and August 1, 2010.
Now you can get any part you want. For example, how many days have elapsed between the two dates:
var days = (a - b) / (60 * 60 * 24 * 1000);
// 60 * 60 * 24 * 1000 is the amount of milisseconds in a day.
// the variable days now equals 30.958333333333332.
That's almost 31 days. You can then round down for 30 days, and use whatever remained to get the amounts of hours, minutes etc.
Get the difference between two dates in a human way
This function is capable of returning natural-language-like text. Use it to get responses like:
"4 years, 1 month and 11 days"
"1 year and 2 months"
"11 months and 20 days"
"12 days"
IMPORTANT: date-fns is a dependency
Just copy the code below and plug in a past date into our getElapsedTime function! It will compare the entered date against the present time and return your human-like responses.
import * as dateFns from "https://cdn.skypack.dev/date-fns#2.22.1";
function getElapsedTime(pastDate) {
const duration = dateFns.intervalToDuration({
start: new Date(pastDate),
end: new Date(),
});
let [years, months, days] = ["", "", ""];
if (duration.years > 0) {
years = duration.years === 1 ? "1 year" : `${duration.years} years`;
}
if (duration.months > 0) {
months = duration.months === 1 ? "1 month" : `${duration.months} months`;
}
if (duration.days > 0) {
days = duration.days === 1 ? "1 day" : `${duration.days} days`;
}
let response = [years, months, days].filter(Boolean);
switch (response.length) {
case 3:
response[1] += " and";
response[0] += ",";
break;
case 2:
response[0] += " and";
break;
}
return response.join(" ");
}
Yet another solution, based on some PHP code.
The strtotime function, also based on PHP, can be found here: http://phpjs.org/functions/strtotime/.
Date.dateDiff = function(d1, d2) {
d1 /= 1000;
d2 /= 1000;
if (d1 > d2) d2 = [d1, d1 = d2][0];
var diffs = {
year: 0,
month: 0,
day: 0,
hour: 0,
minute: 0,
second: 0
}
$.each(diffs, function(interval) {
while (d2 >= (d3 = Date.strtotime('+1 '+interval, d1))) {
d1 = d3;
++diffs[interval];
}
});
return diffs;
};
Usage:
> d1 = new Date(2000, 0, 1)
Sat Jan 01 2000 00:00:00 GMT+0100 (CET)
> d2 = new Date(2013, 9, 6)
Sun Oct 06 2013 00:00:00 GMT+0200 (CEST)
> Date.dateDiff(d1, d2)
Object {
day: 5
hour: 0
minute: 0
month: 9
second: 0
year: 13
}
Very old thread, I know, but here's my contribution, as the thread is not solved yet.
It takes leap years into consideration and does not asume any fixed number of days per month or year.
It might be flawed in border cases as I haven't tested it thoroughly, but it works for all the dates provided in the original question, thus I'm confident.
function calculate() {
var fromDate = document.getElementById('fromDate').value;
var toDate = document.getElementById('toDate').value;
try {
document.getElementById('result').innerHTML = '';
var result = getDateDifference(new Date(fromDate), new Date(toDate));
if (result && !isNaN(result.years)) {
document.getElementById('result').innerHTML =
result.years + ' year' + (result.years == 1 ? ' ' : 's ') +
result.months + ' month' + (result.months == 1 ? ' ' : 's ') + 'and ' +
result.days + ' day' + (result.days == 1 ? '' : 's');
}
} catch (e) {
console.error(e);
}
}
function getDateDifference(startDate, endDate) {
if (startDate > endDate) {
console.error('Start date must be before end date');
return null;
}
var startYear = startDate.getFullYear();
var startMonth = startDate.getMonth();
var startDay = startDate.getDate();
var endYear = endDate.getFullYear();
var endMonth = endDate.getMonth();
var endDay = endDate.getDate();
// We calculate February based on end year as it might be a leep year which might influence the number of days.
var february = (endYear % 4 == 0 && endYear % 100 != 0) || endYear % 400 == 0 ? 29 : 28;
var daysOfMonth = [31, february, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31];
var startDateNotPassedInEndYear = (endMonth < startMonth) || endMonth == startMonth && endDay < startDay;
var years = endYear - startYear - (startDateNotPassedInEndYear ? 1 : 0);
var months = (12 + endMonth - startMonth - (endDay < startDay ? 1 : 0)) % 12;
// (12 + ...) % 12 makes sure index is always between 0 and 11
var days = startDay <= endDay ? endDay - startDay : daysOfMonth[(12 + endMonth - 1) % 12] - startDay + endDay;
return {
years: years,
months: months,
days: days
};
}
<p><input type="text" name="fromDate" id="fromDate" placeholder="yyyy-mm-dd" value="1999-02-28" /></p>
<p><input type="text" name="toDate" id="toDate" placeholder="yyyy-mm-dd" value="2000-03-01" /></p>
<p><input type="button" name="calculate" value="Calculate" onclick="javascript:calculate();" /></p>
<p />
<p id="result"></p>
let startDate = moment(new Date('2017-05-12')); // yyyy-MM-dd
let endDate = moment(new Date('2018-09-14')); // yyyy-MM-dd
let Years = newDate.diff(date, 'years');
let months = newDate.diff(date, 'months');
let days = newDate.diff(date, 'days');
console.log("Year: " + Years, ", Month: " months-(Years*12), ", Days: " days-(Years*365.25)-((365.25*(days- (Years*12)))/12));
Above snippet will print: Year: 1, Month: 4, Days: 2
Using Plane Javascript:
function dateDiffInDays(start, end) {
var MS_PER_DAY = 1000 * 60 * 60 * 24;
var a = new Date(start);
var b = new Date(end);
const diffTime = Math.abs(a - b);
const diffDays = Math.ceil(diffTime / MS_PER_DAY);
console.log("Days: ", diffDays);
// Discard the time and time-zone information.
const utc1 = Date.UTC(a.getFullYear(), a.getMonth(), a.getDate());
const utc2 = Date.UTC(b.getFullYear(), b.getMonth(), b.getDate());
return Math.floor((utc2 - utc1) / MS_PER_DAY);
}
function dateDiffInDays_Months_Years(start, end) {
var m1 = new Date(start);
var m2 = new Date(end);
var yDiff = m2.getFullYear() - m1.getFullYear();
var mDiff = m2.getMonth() - m1.getMonth();
var dDiff = m2.getDate() - m1.getDate();
if (dDiff < 0) {
var daysInLastFullMonth = getDaysInLastFullMonth(start);
if (daysInLastFullMonth < m1.getDate()) {
dDiff = daysInLastFullMonth + dDiff + (m1.getDate() -
daysInLastFullMonth);
} else {
dDiff = daysInLastFullMonth + dDiff;
}
mDiff--;
}
if (mDiff < 0) {
mDiff = 12 + mDiff;
yDiff--;
}
console.log('Y:', yDiff, ', M:', mDiff, ', D:', dDiff);
}
function getDaysInLastFullMonth(day) {
var d = new Date(day);
console.log(d.getDay() );
var lastDayOfMonth = new Date(d.getFullYear(), d.getMonth() + 1, 0);
console.log('last day of month:', lastDayOfMonth.getDate() ); //
return lastDayOfMonth.getDate();
}
Using moment.js:
function dateDiffUsingMoment(start, end) {
var a = moment(start,'M/D/YYYY');
var b = moment(end,'M/D/YYYY');
var diffDaysMoment = b.diff(a, 'days');
console.log('Moments.js : ', diffDaysMoment);
preciseDiffMoments(a,b);
}
function preciseDiffMoments( a, b) {
var m1= a, m2=b;
m1.add(m2.utcOffset() - m1.utcOffset(), 'minutes'); // shift timezone of m1 to m2
var yDiff = m2.year() - m1.year();
var mDiff = m2.month() - m1.month();
var dDiff = m2.date() - m1.date();
if (dDiff < 0) {
var daysInLastFullMonth = moment(m2.year() + '-' + (m2.month() + 1),
"YYYY-MM").subtract(1, 'M').daysInMonth();
if (daysInLastFullMonth < m1.date()) { // 31/01 -> 2/03
dDiff = daysInLastFullMonth + dDiff + (m1.date() -
daysInLastFullMonth);
} else {
dDiff = daysInLastFullMonth + dDiff;
}
mDiff--;
}
if (mDiff < 0) {
mDiff = 12 + mDiff;
yDiff--;
}
console.log('getMomentum() Y:', yDiff, ', M:', mDiff, ', D:', dDiff);
}
Tested the above functions using following samples:
var sample1 = all('2/13/2018', '3/15/2018'); // {'M/D/YYYY'} 30, Y: 0 , M: 1 , D: 2
console.log(sample1);
var sample2 = all('10/09/2019', '7/7/2020'); // 272, Y: 0 , M: 8 , D: 29
console.log(sample2);
function all(start, end) {
dateDiffInDays(start, end);
dateDiffInDays_Months_Years(start, end);
try {
dateDiffUsingMoment(start, end);
} catch (e) {
console.log(e);
}
}
by using Moment library and some custom logic, we can get the exact date difference
var out;
out = diffDate(new Date('2014-05-10'), new Date('2015-10-10'));
display(out);
out = diffDate(new Date('2014-05-10'), new Date('2015-10-09'));
display(out);
out = diffDate(new Date('2014-05-10'), new Date('2015-09-09'));
display(out);
out = diffDate(new Date('2014-05-10'), new Date('2015-03-09'));
display(out);
out = diffDate(new Date('2014-05-10'), new Date('2016-03-09'));
display(out);
out = diffDate(new Date('2014-05-10'), new Date('2016-03-11'));
display(out);
function diffDate(startDate, endDate) {
var b = moment(startDate),
a = moment(endDate),
intervals = ['years', 'months', 'weeks', 'days'],
out = {};
for (var i = 0; i < intervals.length; i++) {
var diff = a.diff(b, intervals[i]);
b.add(diff, intervals[i]);
out[intervals[i]] = diff;
}
return out;
}
function display(obj) {
var str = '';
for (key in obj) {
str = str + obj[key] + ' ' + key + ' '
}
console.log(str);
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.24.0/moment.js"></script>
I did it using a bunch of functions. Pure JavaScript and precise.
This code includes functions that calculate time difference in days, months and years. One of them can be used to get precise time difference for example X years, Y months, Z days. At the end of code I provided some tests.
How it works:
getDaysDiff():
Transforms time difference from milliseconds to days.
getYearsDiff():
There is no worries for effect of months and days of both dates. The function calculates difference in years by moving dates back and forward.
getMonthsDiff() (This one has nothing to do with question, but the concept is used in calExactTimeDiff() and I thought someone may need such a function so I insert it):
This one is a little tricky. The hard work is to deal with month and day of both dates.
If the endDate's month is more than startDate's, this means another year (12 months) is passed. But this is being taken care of in monthsOfFullYears, so the only thing is needed is to add subtraction of month of endDate and startDate.
If the startDate's month is more than endDate's then there is no another year. So we should get the difference between them. Imagine we want to go from month 10 of the current year to 2 of the next year. We can go like this: 11, 12, 1, 2. So we passed 4 months. This is equal to 12 - (10 - 2). We get difference between the months and subtract it from months of a whole year.
Next step is to take care of days of months. If day of endDate is more than or equal to startDate this means another month is passed. So we add 1 to it. But if it's less, then there is nothing to worry about. But in my code I did not do this. Because when I added difference between months I assumed that the days of months are equal. So I already added 1. Thus if day of endDate is less than startDate, I have to decrease months by 1.
There is an exception: if months are equal and endDate's day is less than startDate's, month should be 11.
I used the same concept in calExactTimeDiff().
Hope to be useful :)
// time difference in Days
function getDaysDiff(startDate = new Date(), endDate = new Date()) {
if (startDate > endDate) [startDate, endDate] = [endDate, startDate];
let timeDiff = endDate - startDate;
let timeDiffInDays = Math.floor(timeDiff / (1000 * 3600 * 24));
return timeDiffInDays;
}
// time difference in Months
function getMonthsDiff(startDate = new Date(), endDate = new Date()) {
let monthsOfFullYears = getYearsDiff(startDate, endDate) * 12;
let months = monthsOfFullYears;
// the variable below is not necessary, but I kept it for understanding of code
// we can use "startDate" instead of it
let yearsAfterStart = new Date(
startDate.getFullYear() + getYearsDiff(startDate, endDate),
startDate.getMonth(),
startDate.getDate()
);
let isDayAhead = endDate.getDate() >= yearsAfterStart.getDate();
if (startDate.getMonth() == endDate.getMonth() && !isDayAhead) {
months = 11;
return months;
}
if (endDate.getMonth() >= yearsAfterStart.getMonth()) {
let diff = endDate.getMonth() - yearsAfterStart.getMonth();
months += (isDayAhead) ? diff : diff - 1;
}
else {
months += isDayAhead
? 12 - (startDate.getMonth() - endDate.getMonth())
: 12 - (startDate.getMonth() - endDate.getMonth()) - 1;
}
return months;
}
// time difference in Years
function getYearsDiff(startDate = new Date(), endDate = new Date()) {
if (startDate > endDate) [startDate, endDate] = [endDate, startDate];
let yearB4End = new Date(
endDate.getFullYear() - 1,
endDate.getMonth(),
endDate.getDate()
);
let year = 0;
year = yearB4End > startDate
? yearB4End.getFullYear() - startDate.getFullYear()
: 0;
let yearsAfterStart = new Date(
startDate.getFullYear() + year + 1,
startDate.getMonth(),
startDate.getDate()
);
if (endDate >= yearsAfterStart) year++;
return year;
}
// time difference in format: X years, Y months, Z days
function calExactTimeDiff(firstDate, secondDate) {
if (firstDate > secondDate)
[firstDate, secondDate] = [secondDate, firstDate];
let monthDiff = 0;
let isDayAhead = secondDate.getDate() >= firstDate.getDate();
if (secondDate.getMonth() >= firstDate.getMonth()) {
let diff = secondDate.getMonth() - firstDate.getMonth();
monthDiff += (isDayAhead) ? diff : diff - 1;
}
else {
monthDiff += isDayAhead
? 12 - (firstDate.getMonth() - secondDate.getMonth())
: 12 - (firstDate.getMonth() - secondDate.getMonth()) - 1;
}
let dayDiff = 0;
if (isDayAhead) {
dayDiff = secondDate.getDate() - firstDate.getDate();
}
else {
let b4EndDate = new Date(
secondDate.getFullYear(),
secondDate.getMonth() - 1,
firstDate.getDate()
)
dayDiff = getDaysDiff(b4EndDate, secondDate);
}
if (firstDate.getMonth() == secondDate.getMonth() && !isDayAhead)
monthDiff = 11;
let exactTimeDiffUnits = {
yrs: getYearsDiff(firstDate, secondDate),
mths: monthDiff,
dys: dayDiff,
};
return `${exactTimeDiffUnits.yrs} years, ${exactTimeDiffUnits.mths} months, ${exactTimeDiffUnits.dys} days`
}
let s = new Date(2012, 4, 12);
let e = new Date(2008, 5, 24);
console.log(calExactTimeDiff(s, e));
s = new Date(2001, 7, 4);
e = new Date(2016, 6, 9);
console.log(calExactTimeDiff(s, e));
s = new Date(2011, 11, 28);
e = new Date(2021, 3, 6);
console.log(calExactTimeDiff(s, e));
s = new Date(2020, 8, 7);
e = new Date(2021, 8, 6);
console.log(calExactTimeDiff(s, e));
There a a couple of npm packages that help in doing this. Below is a list gathered from various sources. I find the date-fns version to be the most simplest.
1. date-fns
You can use intervalToDuration, formatDuration from date-fns to humanize a duration in desired format like below:
import { intervalToDuration, formatDuration } from 'date-fns'
let totalDuration = intervalToDuration({
start: new Date(1929, 0, 15, 12, 0, 0),
end: new Date(1968, 3, 4, 19, 5, 0)
});
let textDuration = formatDuration(totalDuration, { format: ['years', 'months'], delimiter: ', ' })
// Output: "39 years, 2 months"
clone the above code from here for trying it yourself: https://runkit.com/embed/diu9o3qe53j4
2. luxon + humanize-duration
you can use luxon to extract the duration between dates and humanize that using humanize-duration like below:
const DateTime = luxon.DateTime;
const Interval = luxon.Interval;
const start = DateTime.fromSQL("2020-06-19 11:14:00");
const finish = DateTime.fromSQL("2020-06-21 13:11:00");
const formatted = Interval
.fromDateTimes(start, finish)
.toDuration()
.valueOf();
console.log(humanizeDuration(formatted))
// output: 2 days, 1 hour, 57 minutes
console.log(humanizeDuration(formatted, { language: 'es' }))
// output: 2 días, 1 hora, 57 minutos
console.log(humanizeDuration(formatted, { language: 'ru' }))
// output: 2 дня, 1 час, 57 минут
<script src="https://cdn.jsdelivr.net/npm/luxon#1.25.0/build/global/luxon.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/humanize-duration#3.25.1/humanize-duration.min.js"></script>
reference to above code: https://stackoverflow.com/a/65651515/6908282
I would personally use http://www.datejs.com/, really handy. Specifically, look at the time.js file: http://code.google.com/p/datejs/source/browse/trunk/src/time.js
Time span in full Days, Hours, Minutes, Seconds, Milliseconds:
// Extension for Date
Date.difference = function (dateFrom, dateTo) {
var diff = { TotalMs: dateTo - dateFrom };
diff.Days = Math.floor(diff.TotalMs / 86400000);
var remHrs = diff.TotalMs % 86400000;
var remMin = remHrs % 3600000;
var remS = remMin % 60000;
diff.Hours = Math.floor(remHrs / 3600000);
diff.Minutes = Math.floor(remMin / 60000);
diff.Seconds = Math.floor(remS / 1000);
diff.Milliseconds = Math.floor(remS % 1000);
return diff;
};
// Usage
var a = new Date(2014, 05, 12, 00, 5, 45, 30); //a: Thu Jun 12 2014 00:05:45 GMT+0400
var b = new Date(2014, 02, 12, 00, 0, 25, 0); //b: Wed Mar 12 2014 00:00:25 GMT+0400
var diff = Date.difference(b, a);
/* diff: {
Days: 92
Hours: 0
Minutes: 5
Seconds: 20
Milliseconds: 30
TotalMs: 7949120030
} */
Neither of the codes work for me, so I use this instead for months and days:
function monthDiff(d2, d1) {
var months;
months = (d2.getFullYear() - d1.getFullYear()) * 12;
months -= d1.getMonth() + 1;
months += d2.getMonth() + 1;
return months <= 0 ? 0 : months;
}
function daysInMonth(date) {
return new Date(date.getYear(), date.getMonth() + 1, 0).getDate();
}
function diffDate(date1, date2) {
if (date2 && date2.getTime() && !isNaN(date2.getTime())) {
var months = monthDiff(date1, date2);
var days = 0;
if (date1.getUTCDate() >= date2.getUTCDate()) {
days = date1.getUTCDate() - date2.getUTCDate();
}
else {
months--;
days = date1.getUTCDate() - date2.getUTCDate() + daysInMonth(date2);
}
// Use the variables months and days how you need them.
}
}
The following is an algorithm which gives correct but not totally precise since it does not take into account leap year. It also assumes 30 days in a month. A good usage for example is if someone lives in an address from 12/11/2010 to 11/10/2011, it can quickly tells that the person lives there for 10 months and 29 days. From 12/11/2010 to 11/12/2011 is 11 months and 1 day. For certain types of applications, that kind of precision is sufficient. This is for those types of applications because it aims for simplicity:
var datediff = function(start, end) {
var diff = { years: 0, months: 0, days: 0 };
var timeDiff = end - start;
if (timeDiff > 0) {
diff.years = end.getFullYear() - start.getFullYear();
diff.months = end.getMonth() - start.getMonth();
diff.days = end.getDate() - start.getDate();
if (diff.months < 0) {
diff.years--;
diff.months += 12;
}
if (diff.days < 0) {
diff.months = Math.max(0, diff.months - 1);
diff.days += 30;
}
}
return diff;
};
Unit tests
To calculate the difference between two dates in Years, Months, Days, Minutes, Seconds, Milliseconds using TypeScript/ JavaScript
dateDifference(actualDate) {
// Calculate time between two dates:
const date1 = actualDate; // the date you already commented/ posted
const date2: any = new Date(); // today
let r = {}; // object for clarity
let message: string;
const diffInSeconds = Math.abs(date2 - date1) / 1000;
const days = Math.floor(diffInSeconds / 60 / 60 / 24);
const hours = Math.floor(diffInSeconds / 60 / 60 % 24);
const minutes = Math.floor(diffInSeconds / 60 % 60);
const seconds = Math.floor(diffInSeconds % 60);
const milliseconds =
Math.round((diffInSeconds - Math.floor(diffInSeconds)) * 1000);
const months = Math.floor(days / 31);
const years = Math.floor(months / 12);
// the below object is just optional
// if you want to return an object instead of a message
r = {
years: years,
months: months,
days: days,
hours: hours,
minutes: minutes,
seconds: seconds,
milliseconds: milliseconds
};
// check if difference is in years or months
if (years === 0 && months === 0) {
// show in days if no years / months
if (days > 0) {
if (days === 1) {
message = days + ' day';
} else { message = days + ' days'; }
} else if (hours > 0) {
if (hours === 1) {
message = hours + ' hour';
} else {
message = hours + ' hours';
}
} else {
// show in minutes if no years / months / days
if (minutes === 1) {
message = minutes + ' minute';
} else {message = minutes + ' minutes';}
}
} else if (years === 0 && months > 0) {
// show in months if no years
if (months === 1) {
message = months + ' month';
} else {message = months + ' months';}
} else if (years > 0) {
// show in years if years exist
if (years === 1) {
message = years + ' year';
} else {message = years + ' years';}
}
return 'Posted ' + message + ' ago';
// this is the message a user see in the view
}
However, you can update the above logic for the message to show seconds and milliseconds too or else use the object 'r' to format the message whatever way you want.
If you want to directly copy the code, you can view my gist with the above code here
I know it is an old thread, but I'd like to put my 2 cents based on the answer by #Pawel Miech.
It is true that you need to convert the difference into milliseconds, then you need to make some math. But notice that, you need to do the math in backward manner, i.e. you need to calculate years, months, days, hours then minutes.
I used to do some thing like this:
var mins;
var hours;
var days;
var months;
var years;
var diff = new Date() - new Date(yourOldDate);
// yourOldDate may be is coming from DB, for example, but it should be in the correct format ("MM/dd/yyyy hh:mm:ss:fff tt")
years = Math.floor((diff) / (1000 * 60 * 60 * 24 * 365));
diff = Math.floor((diff) % (1000 * 60 * 60 * 24 * 365));
months = Math.floor((diff) / (1000 * 60 * 60 * 24 * 30));
diff = Math.floor((diff) % (1000 * 60 * 60 * 24 * 30));
days = Math.floor((diff) / (1000 * 60 * 60 * 24));
diff = Math.floor((diff) % (1000 * 60 * 60 * 24));
hours = Math.floor((diff) / (1000 * 60 * 60));
diff = Math.floor((diff) % (1000 * 60 * 60));
mins = Math.floor((diff) / (1000 * 60));
But, of course, this is not precise because it assumes that all years have 365 days and all months have 30 days, which is not true in all cases.
Its very simple please use the code below and it will give the difference in that format according to this //3 years 9 months 3 weeks 5 days 15 hours 50 minutes
Date.getFormattedDateDiff = function(date1, date2) {
var b = moment(date1),
a = moment(date2),
intervals = ['years','months','weeks','days'],
out = [];
for(var i=0; i<intervals.length; i++){
var diff = a.diff(b, intervals[i]);
b.add(diff, intervals[i]);
out.push(diff + ' ' + intervals[i]);
}
return out.join(', ');
};
var today = new Date(),
newYear = new Date(today.getFullYear(), 0, 1),
y2k = new Date(2000, 0, 1);
//(AS OF NOV 29, 2016)
//Time since New Year: 0 years, 10 months, 4 weeks, 0 days
console.log( 'Time since New Year: ' + Date.getFormattedDateDiff(newYear, today) );
//Time since Y2K: 16 years, 10 months, 4 weeks, 0 days
console.log( 'Time since Y2K: ' + Date.getFormattedDateDiff(y2k, today) );
This code should give you desired results
//************************** Enter your dates here **********************//
var startDate = "10/05/2014";
var endDate = "11/3/2016"
//******* and press "Run", you will see the result in a popup *********//
var noofdays = 0;
var sdArr = startDate.split("/");
var startDateDay = parseInt(sdArr[0]);
var startDateMonth = parseInt(sdArr[1]);
var startDateYear = parseInt(sdArr[2]);
sdArr = endDate.split("/")
var endDateDay = parseInt(sdArr[0]);
var endDateMonth = parseInt(sdArr[1]);
var endDateYear = parseInt(sdArr[2]);
console.log(startDateDay+' '+startDateMonth+' '+startDateYear);
var yeardays = 365;
var monthArr = [31,,31,30,31,30,31,31,30,31,30,31];
var noofyears = 0
var noofmonths = 0;
if((startDateYear%4)==0) monthArr[1]=29;
else monthArr[1]=28;
if(startDateYear == endDateYear){
noofyears = 0;
noofmonths = getMonthDiff(startDate,endDate);
if(noofmonths < 0) noofmonths = 0;
noofdays = getDayDiff(startDate,endDate);
}else{
if(endDateMonth < startDateMonth){
noofyears = (endDateYear - startDateYear)-1;
if(noofyears < 1) noofyears = 0;
}else{
noofyears = endDateYear - startDateYear;
}
noofmonths = getMonthDiff(startDate,endDate);
if(noofmonths < 0) noofmonths = 0;
noofdays = getDayDiff(startDate,endDate);
}
alert(noofyears+' year, '+ noofmonths+' months, '+ noofdays+' days');
function getDayDiff(startDate,endDate){
if(endDateDay >=startDateDay){
noofdays = 0;
if(endDateDay > startDateDay) {
noofdays = endDateDay - startDateDay;
}
}else{
if((endDateYear%4)==0) {
monthArr[1]=29;
}else{
monthArr[1] = 28;
}
if(endDateMonth != 1)
noofdays = (monthArr[endDateMonth-2]-startDateDay) + endDateDay;
else
noofdays = (monthArr[11]-startDateDay) + endDateDay;
}
return noofdays;
}
function getMonthDiff(startDate,endDate){
if(endDateMonth > startDateMonth){
noofmonths = endDateMonth - startDateMonth;
if(endDateDay < startDateDay){
noofmonths--;
}
}else{
noofmonths = (12-startDateMonth) + endDateMonth;
if(endDateDay < startDateDay){
noofmonths--;
}
}
return noofmonths;
}
https://jsfiddle.net/moremanishk/hk8c419f/
You should try using date-fns. Here's how I did it using intervalToDuration and formatDuration functions from date-fns.
let startDate = Date.parse("2010-10-01 00:00:00 UTC");
let endDate = Date.parse("2020-11-01 00:00:00 UTC");
let duration = intervalToDuration({start: startDate, end: endDate});
let durationInWords = formatDuration(duration, {format: ["years", "months", "days"]}); //output: 10 years 1 month
since I had to use moment-hijri (hijri calendar) and couldn't use moment.diff() method, I came up with this solution. can also be used with moment.js
var momenti = require('moment-hijri')
//calculate hijri
var strt = await momenti(somedateobject)
var until = await momenti()
var years = await 0
var months = await 0
var days = await 0
while(strt.valueOf() < until.valueOf()){
await strt.add(1, 'iYear');
await years++
}
await strt.subtract(1, 'iYear');
await years--
while(strt.valueOf() < until.valueOf()){
await strt.add(1, 'iMonth');
await months++
}
await strt.subtract(1, 'iMonth');
await months--
while(strt.valueOf() < until.valueOf()){
await strt.add(1, 'day');
await days++
}
await strt.subtract(1, 'day');
await days--
await console.log(years)
await console.log(months)
await console.log(days)
A solution with the ECMAScript "Temporal API" which is currently (as of 5th March 2022) in Stage 3 of Active Proposals, which will the method we will do this in the future (soon).
Here is a solution with the current temporal-polyfill
<script type='module'>
import * as TemporalModule from 'https://cdn.jsdelivr.net/npm/#js-temporal/polyfill#0.3.0/dist/index.umd.js'
const Temporal = temporal.Temporal;
//----------------------------------------
function dateDiff(start, end, maxUnit) {
return (Temporal.PlainDate.from(start).until(Temporal.PlainDate.from(end),{largestUnit:maxUnit}).toString()).match(/(\d*Y)|(\d*M)|(\d*D)/g).join(" ");
}
//----------------------------------------
console.log("Diff in (years, months, days): ",dateDiff("1963-02-03","2022-03-06","year"))
console.log("Diff in (months, days) : ",dateDiff("1963-02-03","2022-03-06","month"))
console.log("Diff in (days) : ",dateDiff("1963-02-03","2022-03-06","day"))
</script>
Your expected output is not correct. For example difference between '2014-05-10' and '2015-03-09' is not 9 months, 27 days
the correct answer is
(05-10 to 05-31) = 21 days
(2014-06 to 2015-03) = 9 months
(03-01 to 03-09) = 9 days
total is 9 months and 30 days
WARNING: An ideal function would be aware of leap years and days count in every month, but I found the results of this function accurate enough for my current task, so I shared it with you
function diffDate(date1, date2)
{
var daysDiff = Math.ceil((Math.abs(date1 - date2)) / (1000 * 60 * 60 * 24));
var years = Math.floor(daysDiff / 365.25);
var remainingDays = Math.floor(daysDiff - (years * 365.25));
var months = Math.floor((remainingDays / 365.25) * 12);
var days = Math.ceil(daysDiff - (years * 365.25 + (months / 12 * 365.25)));
return {
daysAll: daysDiff,
years: years,
months: months,
days:days
}
}
console.log(diffDate(new Date('2014-05-10'), new Date('2015-10-10')));
console.log(diffDate(new Date('2014-05-10'), new Date('2015-10-09')));
console.log(diffDate(new Date('2014-05-10'), new Date('2015-09-09')));
console.log(diffDate(new Date('2014-05-10'), new Date('2015-03-09')));
console.log(diffDate(new Date('2014-05-10'), new Date('2016-03-09')));
console.log(diffDate(new Date('2014-05-10'), new Date('2016-03-11')));

Fix Date.getWeek() function errors on final days of year?

I am using a function to get the weekNumber within my app, returning an integer as a result, which works as intended, the code is:
Date.prototype.getWeek = function(dowOffset) {
dowOffset = Number.isInteger(dowOffset)? dowOffset : 0; //default dowOffset to zero
var newYear = new Date(this.getFullYear(), 0, 1);
var day = newYear.getDay() - dowOffset; //the day of week the year begins on
day = (day >= 0 ? day : day + 7);
var daynum = Math.floor((this.getTime() - newYear.getTime() -
(this.getTimezoneOffset() - newYear.getTimezoneOffset()) * 60000) / 86400000) + 1;
var weeknum;
//if the year starts before the middle of a week
if (day < 4) {
weeknum = Math.floor((daynum + day - 1) / 7) + 1;
if (weeknum > 52) {
nYear = new Date(this.getFullYear() + 1, 0, 1);
nday = nYear.getDay() - dowOffset;
nday = nday >= 0 ? nday : nday + 7;
/*if the next year starts before the middle of
the week, it is week #1 of that year*/
weeknum = nday < 4 ? 1 : 53;
}
} else {
weeknum = Math.floor((daynum + day - 1) / 7);
}
return weeknum;
};
for (var d, i=10; i; i--) {
d = new Date(2029 - i, 11, 31);
console.log(d.toString() + ' which is week ' + d.getWeek(1));
}
(Answer taken from JavaScript Date.getWeek()
This all works as intended, yet if the final days of the year (say December 30th & December 31st), fall into the first week of the year, it does not read them within week 1, instead, errors returning no result?
How would I alter this code to ensure that the result will return the first week number when the days could possibly be within the final month of the year?

How to get current week number in javascript? [duplicate]

How do I get the current weeknumber of the year, like PHP's date('W')?
It should be the ISO-8601 week number of year, weeks starting on Monday.
You should be able to get what you want here: http://www.merlyn.demon.co.uk/js-date6.htm#YWD.
A better link on the same site is: Working with weeks.
Edit
Here is some code based on the links provided and that posted eariler by Dommer. It has been lightly tested against results at http://www.merlyn.demon.co.uk/js-date6.htm#YWD. Please test thoroughly, no guarantee provided.
Edit 2017
There was an issue with dates during the period that daylight saving was observed and years where 1 Jan was Friday. Fixed by using all UTC methods. The following returns identical results to Moment.js.
/* For a given date, get the ISO week number
*
* Based on information at:
*
* THIS PAGE (DOMAIN EVEN) DOESN'T EXIST ANYMORE UNFORTUNATELY
* http://www.merlyn.demon.co.uk/weekcalc.htm#WNR
*
* Algorithm is to find nearest thursday, it's year
* is the year of the week number. Then get weeks
* between that date and the first day of that year.
*
* Note that dates in one year can be weeks of previous
* or next year, overlap is up to 3 days.
*
* e.g. 2014/12/29 is Monday in week 1 of 2015
* 2012/1/1 is Sunday in week 52 of 2011
*/
function getWeekNumber(d) {
// Copy date so don't modify original
d = new Date(Date.UTC(d.getFullYear(), d.getMonth(), d.getDate()));
// Set to nearest Thursday: current date + 4 - current day number
// Make Sunday's day number 7
d.setUTCDate(d.getUTCDate() + 4 - (d.getUTCDay()||7));
// Get first day of year
var yearStart = new Date(Date.UTC(d.getUTCFullYear(),0,1));
// Calculate full weeks to nearest Thursday
var weekNo = Math.ceil(( ( (d - yearStart) / 86400000) + 1)/7);
// Return array of year and week number
return [d.getUTCFullYear(), weekNo];
}
var result = getWeekNumber(new Date());
document.write('It\'s currently week ' + result[1] + ' of ' + result[0]);
Hours are zeroed when creating the "UTC" date.
Minimized, prototype version (returns only week-number):
Date.prototype.getWeekNumber = function(){
var d = new Date(Date.UTC(this.getFullYear(), this.getMonth(), this.getDate()));
var dayNum = d.getUTCDay() || 7;
d.setUTCDate(d.getUTCDate() + 4 - dayNum);
var yearStart = new Date(Date.UTC(d.getUTCFullYear(),0,1));
return Math.ceil((((d - yearStart) / 86400000) + 1)/7)
};
document.write('The current ISO week number is ' + new Date().getWeekNumber());
Test section
In this section, you can enter any date in YYYY-MM-DD format and check that this code gives the same week number as Moment.js ISO week number (tested over 50 years from 2000 to 2050).
Date.prototype.getWeekNumber = function(){
var d = new Date(Date.UTC(this.getFullYear(), this.getMonth(), this.getDate()));
var dayNum = d.getUTCDay() || 7;
d.setUTCDate(d.getUTCDate() + 4 - dayNum);
var yearStart = new Date(Date.UTC(d.getUTCFullYear(),0,1));
return Math.ceil((((d - yearStart) / 86400000) + 1)/7)
};
function checkWeek() {
var s = document.getElementById('dString').value;
var m = moment(s, 'YYYY-MM-DD');
document.getElementById('momentWeek').value = m.format('W');
document.getElementById('answerWeek').value = m.toDate().getWeekNumber();
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.18.1/moment.min.js"></script>
Enter date YYYY-MM-DD: <input id="dString" value="2021-02-22">
<button onclick="checkWeek(this)">Check week number</button><br>
Moment: <input id="momentWeek" readonly><br>
Answer: <input id="answerWeek" readonly>
You can use momentjs library also:
moment().format('W')
Not ISO-8601 week number but if the search engine pointed you here anyway.
As said above but without a class:
let now = new Date();
let onejan = new Date(now.getFullYear(), 0, 1);
let week = Math.ceil((((now.getTime() - onejan.getTime()) / 86400000) + onejan.getDay() + 1) / 7);
console.log(week);
Accordily http://javascript.about.com/library/blweekyear.htm
Date.prototype.getWeek = function() {
var onejan = new Date(this.getFullYear(), 0, 1);
var millisecsInDay = 86400000;
return Math.ceil((((this - onejan) / millisecsInDay) + onejan.getDay() + 1) / 7);
};
let d = new Date(2020,11,30);
for (let i=0; i<14; i++) {
console.log(`${d.toDateString()} is week ${d.getWeek()}`);
d.setDate(d.getDate() + 1);
}
Jacob Wright's Date.format() library implements date formatting in the style of PHP's date() function and supports the ISO-8601 week number:
new Date().format('W');
It may be a bit overkill for just a week number, but it does support PHP style formatting and is quite handy if you'll be doing a lot of this.
The code below calculates the correct ISO 8601 week number. It matches PHP's date("W") for every week between 1/1/1970 and 1/1/2100.
/**
* Get the ISO week date week number
*/
Date.prototype.getWeek = function () {
// Create a copy of this date object
var target = new Date(this.valueOf());
// ISO week date weeks start on Monday, so correct the day number
var dayNr = (this.getDay() + 6) % 7;
// ISO 8601 states that week 1 is the week with the first Thursday of that year
// Set the target date to the Thursday in the target week
target.setDate(target.getDate() - dayNr + 3);
// Store the millisecond value of the target date
var firstThursday = target.valueOf();
// Set the target to the first Thursday of the year
// First, set the target to January 1st
target.setMonth(0, 1);
// Not a Thursday? Correct the date to the next Thursday
if (target.getDay() !== 4) {
target.setMonth(0, 1 + ((4 - target.getDay()) + 7) % 7);
}
// The week number is the number of weeks between the first Thursday of the year
// and the Thursday in the target week (604800000 = 7 * 24 * 3600 * 1000)
return 1 + Math.ceil((firstThursday - target) / 604800000);
}
Source: Taco van den Broek
If you're not into extending prototypes, then here's a function:
function getWeek(date) {
if (!(date instanceof Date)) date = new Date();
// ISO week date weeks start on Monday, so correct the day number
var nDay = (date.getDay() + 6) % 7;
// ISO 8601 states that week 1 is the week with the first Thursday of that year
// Set the target date to the Thursday in the target week
date.setDate(date.getDate() - nDay + 3);
// Store the millisecond value of the target date
var n1stThursday = date.valueOf();
// Set the target to the first Thursday of the year
// First, set the target to January 1st
date.setMonth(0, 1);
// Not a Thursday? Correct the date to the next Thursday
if (date.getDay() !== 4) {
date.setMonth(0, 1 + ((4 - date.getDay()) + 7) % 7);
}
// The week number is the number of weeks between the first Thursday of the year
// and the Thursday in the target week (604800000 = 7 * 24 * 3600 * 1000)
return 1 + Math.ceil((n1stThursday - date) / 604800000);
}
Sample usage:
getWeek(); // Returns 37 (or whatever the current week is)
getWeek(new Date('Jan 2, 2011')); // Returns 52
getWeek(new Date('Jan 1, 2016')); // Returns 53
getWeek(new Date('Jan 4, 2016')); // Returns 1
getWeekOfYear: function(date) {
var target = new Date(date.valueOf()),
dayNumber = (date.getUTCDay() + 6) % 7,
firstThursday;
target.setUTCDate(target.getUTCDate() - dayNumber + 3);
firstThursday = target.valueOf();
target.setUTCMonth(0, 1);
if (target.getUTCDay() !== 4) {
target.setUTCMonth(0, 1 + ((4 - target.getUTCDay()) + 7) % 7);
}
return Math.ceil((firstThursday - target) / (7 * 24 * 3600 * 1000)) + 1;
}
Following code is timezone-independent (UTC dates used) and works according to the https://en.wikipedia.org/wiki/ISO_8601
Get the weeknumber of any given Date
function week(year,month,day) {
function serial(days) { return 86400000*days; }
function dateserial(year,month,day) { return (new Date(year,month-1,day).valueOf()); }
function weekday(date) { return (new Date(date)).getDay()+1; }
function yearserial(date) { return (new Date(date)).getFullYear(); }
var date = year instanceof Date ? year.valueOf() : typeof year === "string" ? new Date(year).valueOf() : dateserial(year,month,day),
date2 = dateserial(yearserial(date - serial(weekday(date-serial(1))) + serial(4)),1,3);
return ~~((date - date2 + serial(weekday(date2) + 5))/ serial(7));
}
Example
console.log(
week(2016, 06, 11),//23
week(2015, 9, 26),//39
week(2016, 1, 1),//53
week(2016, 1, 4),//1
week(new Date(2016, 0, 4)),//1
week("11 january 2016")//2
);
I found useful the Java SE's SimpleDateFormat class described on Oracle's specification:
http://goo.gl/7MbCh5. In my case in Google Apps Script it worked like this:
function getWeekNumber() {
var weekNum = parseInt(Utilities.formatDate(new Date(), "GMT", "w"));
Logger.log(weekNum);
}
For example in a spreadsheet macro you can retrieve the actual timezone of the file:
function getWeekNumber() {
var weekNum = parseInt(Utilities.formatDate(new Date(), SpreadsheetApp.getActiveSpreadsheet().getSpreadsheetTimeZone(), "w"));
Logger.log(weekNum);
}
This adds "getWeek" method to Date.prototype which returns number of week from the beginning of the year. The argument defines which day of the week to consider the first. If no argument passed, first day is assumed Sunday.
/**
* Get week number in the year.
* #param {Integer} [weekStart=0] First day of the week. 0-based. 0 for Sunday, 6 for Saturday.
* #return {Integer} 0-based number of week.
*/
Date.prototype.getWeek = function(weekStart) {
var januaryFirst = new Date(this.getFullYear(), 0, 1);
if(weekStart !== undefined && (typeof weekStart !== 'number' || weekStart % 1 !== 0 || weekStart < 0 || weekStart > 6)) {
throw new Error('Wrong argument. Must be an integer between 0 and 6.');
}
weekStart = weekStart || 0;
return Math.floor((((this - januaryFirst) / 86400000) + januaryFirst.getDay() - weekStart) / 7);
};
If you are already in an Angular project you could use $filter('date').
For example:
var myDate = new Date();
var myWeek = $filter('date')(myDate, 'ww');
The code snippet which works pretty well for me is this one:
var yearStart = +new Date(d.getFullYear(), 0, 1);
var today = +new Date(d.getFullYear(),d.getMonth(),d.getDate());
var dayOfYear = ((today - yearStart + 1) / 86400000);
return Math.ceil(dayOfYear / 7).toString();
Note:
d is my Date for which I want the current week number.
The + converts the Dates into numbers (working with TypeScript).
With Luxon (https://github.com/moment/luxon) :
import { DateTime } from 'luxon';
const week: number = DateTime.fromJSDate(new Date()).weekNumber;
This week number thing has been a real pain in the a**. Most trivial solutions around the web didn't really work for me as they worked most of the time but all of them broke at some point, especially when year changed and last week of the year was suddenly next year's first week etc. Even Angular's date filter showed incorrect data (it was the 1st week of next year, Angular gave week 53).
Note: The examples are designed to work with European weeks (Mon first)!
getWeek()
Date.prototype.getWeek = function(){
// current week's Thursday
var curWeek = new Date(this.getTime());
curWeek.setDay(4);
// current year's first week's Thursday
var firstWeek = new Date(curWeek.getFullYear(), 0, 4);
firstWeek.setDay(4);
return (curWeek.getDayIndex() - firstWeek.getDayIndex()) / 7 + 1;
};
setDay()
/**
* Make a setDay() prototype for Date
* Sets week day for the date
*/
Date.prototype.setDay = function(day){
// Get day and make Sunday to 7
var weekDay = this.getDay() || 7;
var distance = day - weekDay;
this.setDate(this.getDate() + distance);
return this;
}
getDayIndex()
/*
* Returns index of given date (from Jan 1st)
*/
Date.prototype.getDayIndex = function(){
var start = new Date(this.getFullYear(), 0, 0);
var diff = this - start;
var oneDay = 86400000;
return Math.floor(diff / oneDay);
};
I have tested this and it seems to be working very well but if you notice a flaw in it, please let me know.
Here is my implementation for calculating the week number in JavaScript. corrected for summer and winter time offsets as well.
I used the definition of the week from this article: ISO 8601
Weeks are from mondays to sunday, and january 4th is always in the first week of the year.
// add get week prototype functions
// weeks always start from monday to sunday
// january 4th is always in the first week of the year
Date.prototype.getWeek = function () {
year = this.getFullYear();
var currentDotw = this.getWeekDay();
if (this.getMonth() == 11 && this.getDate() - currentDotw > 28) {
// if true, the week is part of next year
return this.getWeekForYear(year + 1);
}
if (this.getMonth() == 0 && this.getDate() + 6 - currentDotw < 4) {
// if true, the week is part of previous year
return this.getWeekForYear(year - 1);
}
return this.getWeekForYear(year);
}
// returns a zero based day, where monday = 0
// all weeks start with monday
Date.prototype.getWeekDay = function () {
return (this.getDay() + 6) % 7;
}
// corrected for summer/winter time
Date.prototype.getWeekForYear = function (year) {
var currentDotw = this.getWeekDay();
var fourjan = new Date(year, 0, 4);
var firstDotw = fourjan.getWeekDay();
var dayTotal = this.getDaysDifferenceCorrected(fourjan) // the difference in days between the two dates.
// correct for the days of the week
dayTotal += firstDotw; // the difference between the current date and the first monday of the first week,
dayTotal -= currentDotw; // the difference between the first monday and the current week's monday
// day total should be a multiple of 7 now
var weeknumber = dayTotal / 7 + 1; // add one since it gives a zero based week number.
return weeknumber;
}
// corrected for timezones and offset
Date.prototype.getDaysDifferenceCorrected = function (other) {
var millisecondsDifference = (this - other);
// correct for offset difference. offsets are in minutes, the difference is in milliseconds
millisecondsDifference += (other.getTimezoneOffset()- this.getTimezoneOffset()) * 60000;
// return day total. 1 day is 86400000 milliseconds, floor the value to return only full days
return Math.floor(millisecondsDifference / 86400000);
}
for testing i used the following JavaScript tests in Qunit
var runweekcompare = function(result, expected) {
equal(result, expected,'Week nr expected value: ' + expected + ' Actual value: ' + result);
}
test('first week number test', function () {
expect(5);
var temp = new Date(2016, 0, 4); // is the monday of the first week of the year
runweekcompare(temp.getWeek(), 1);
var temp = new Date(2016, 0, 4, 23, 50); // is the monday of the first week of the year
runweekcompare(temp.getWeek(), 1);
var temp = new Date(2016, 0, 10, 23, 50); // is the sunday of the first week of the year
runweekcompare(temp.getWeek(), 1);
var temp = new Date(2016, 0, 11, 23, 50); // is the second week of the year
runweekcompare(temp.getWeek(), 2);
var temp = new Date(2016, 1, 29, 23, 50); // is the 9th week of the year
runweekcompare(temp.getWeek(), 9);
});
test('first day is part of last years last week', function () {
expect(2);
var temp = new Date(2016, 0, 1, 23, 50); // is the first last week of the previous year
runweekcompare(temp.getWeek(), 53);
var temp = new Date(2011, 0, 2, 23, 50); // is the first last week of the previous year
runweekcompare(temp.getWeek(), 52);
});
test('last day is part of next years first week', function () {
var temp = new Date(2013, 11, 30); // is part of the first week of 2014
runweekcompare(temp.getWeek(), 1);
});
test('summer winter time change', function () {
expect(2);
var temp = new Date(2000, 2, 26);
runweekcompare(temp.getWeek(), 12);
var temp = new Date(2000, 2, 27);
runweekcompare(temp.getWeek(), 13);
});
test('full 20 year test', function () {
//expect(20 * 12 * 28 * 2);
for (i = 2000; i < 2020; i++) {
for (month = 0; month < 12; month++) {
for (day = 1; day < 29 ; day++) {
var temp = new Date(i, month, day);
var expectedweek = temp.getWeek();
var temp2 = new Date(i, month, day, 23, 50);
var resultweek = temp.getWeek();
equal(expectedweek, Math.round(expectedweek), 'week number whole number expected ' + Math.round(expectedweek) + ' resulted week nr ' + expectedweek);
equal(resultweek, expectedweek, 'Week nr expected value: ' + expectedweek + ' Actual value: ' + resultweek + ' for year ' + i + ' month ' + month + ' day ' + day);
}
}
}
});
Here is a slight adaptation for Typescript that will also return the dates for the week start and week end. I think it's common to have to display those in a user interface, since people don't usually remember week numbers.
function getWeekNumber(d: Date) {
// Copy date so don't modify original
d = new Date(Date.UTC(d.getFullYear(), d.getMonth(), d.getDate()));
// Set to nearest Thursday: current date + 4 - current day number Make
// Sunday's day number 7
d.setUTCDate(d.getUTCDate() + 4 - (d.getUTCDay() || 7));
// Get first day of year
const yearStart = new Date(Date.UTC(d.getUTCFullYear(), 0, 1));
// Calculate full weeks to nearest Thursday
const weekNo = Math.ceil(
((d.getTime() - yearStart.getTime()) / 86400000 + 1) / 7
);
const weekStartDate = new Date(d.getTime());
weekStartDate.setUTCDate(weekStartDate.getUTCDate() - 3);
const weekEndDate = new Date(d.getTime());
weekEndDate.setUTCDate(weekEndDate.getUTCDate() + 3);
return [d.getUTCFullYear(), weekNo, weekStartDate, weekEndDate] as const;
}
This is my typescript implementation which I tested against some dates. This implementation allows you to set the first day of the week to any day.
//sunday = 0, monday = 1, ...
static getWeekNumber(date: Date, firstDay = 1): number {
const d = new Date(date.getTime());
d.setHours(0, 0, 0, 0);
//Set to first day of the week since it is the same weeknumber
while(d.getDay() != firstDay){
d.setDate(d.getDate() - 1);
}
const dayOfYear = this.getDayOfYear(d);
let weken = Math.floor(dayOfYear/7);
// add an extra week if 4 or more days are in this year.
const daysBefore = ((dayOfYear % 7) - 1);
if(daysBefore >= 4){
weken += 1;
}
//if the last 3 days onf the year,it is the first week
const t = new Date(d.getTime());
t.setDate(t.getDate() + 3);
if(t.getFullYear() > d.getFullYear()){
return 1;
}
weken += 1;
return weken;
}
private static getDayOfYear(date: Date){
const start = new Date(date.getFullYear(), 0, 0);
const diff = (date.getTime() - start.getTime()) + ((start.getTimezoneOffset() - date.getTimezoneOffset()) * 60 * 1000);
const oneDay = 1000 * 60 * 60 * 24;
const day = Math.floor(diff / oneDay);
return day;
}
Tests:
describe('getWeeknumber', () => {
it('should be ok for 0 sunday', () => {
expect(DateUtils.getWeekNumber(new Date(2015, 0, 4), 0)).toBe(1);
expect(DateUtils.getWeekNumber(new Date(2017, 0, 1), 0)).toBe(1);
expect(DateUtils.getWeekNumber(new Date(2017, 0, 2), 0)).toBe(1);
expect(DateUtils.getWeekNumber(new Date(2017, 0, 8), 0)).toBe(2);
expect(DateUtils.getWeekNumber(new Date(2017, 0, 9), 0)).toBe(2);
expect(DateUtils.getWeekNumber(new Date(2020, 11, 28), 0)).toBe(53);
expect(DateUtils.getWeekNumber(new Date(2020, 11, 29), 0)).toBe(53);
expect(DateUtils.getWeekNumber(new Date(2020, 11, 30), 0)).toBe(53);
expect(DateUtils.getWeekNumber(new Date(2020, 11, 31), 0)).toBe(53);
expect(DateUtils.getWeekNumber(new Date(2022, 0, 3), 0)).toBe(1);
});
it('should be ok for monday 1 default', () => {
expect(DateUtils.getWeekNumber(new Date(2015, 0, 4), 1)).toBe(1);
expect(DateUtils.getWeekNumber(new Date(2017, 0, 1), 1)).toBe(52);
expect(DateUtils.getWeekNumber(new Date(2017, 0, 2), 1)).toBe(1);
expect(DateUtils.getWeekNumber(new Date(2017, 0, 8), 1)).toBe(1);
expect(DateUtils.getWeekNumber(new Date(2017, 0, 9), 1)).toBe(2);
expect(DateUtils.getWeekNumber(new Date(2020, 11, 28), 1)).toBe(53);
expect(DateUtils.getWeekNumber(new Date(2020, 11, 29), 1)).toBe(53);
expect(DateUtils.getWeekNumber(new Date(2020, 11, 30), 1)).toBe(53);
expect(DateUtils.getWeekNumber(new Date(2020, 11, 31), 1)).toBe(53);
expect(DateUtils.getWeekNumber(new Date(2022, 0, 3), 1)).toBe(1);
});
});
I tried a lot to get the shortest code to get the weeknumber ISO-conform.
Date.prototype.getWeek=function(){
var date=new Date(this);
date.setHours(0,0,0,0);
return Math.round(((date.setDate(this.getDate()+2-(this.getDay()||7))-date.setMonth(0,4))/8.64e7+3+(date.getDay()||7))/7)+"/"+date.getFullYear();}
The variable date is necessary to avoid to alter the original this. I used the return values of setDate() and setMonth() to dispense with getTime() to save code length and I used an expontial number for milliseconds of a day instead of a multiplication of single elements or a number with five zeros. this is Date or Number of milliseconds, return value is String e.g. "49/2017".
Another library-based option: use d3-time-format:
const formatter = d3.timeFormat('%U');
const weekNum = formatter(new Date());
Shortest workaround for Angular2+ DatePipe, adjusted for ISO-8601:
import {DatePipe} from "#angular/common";
public rightWeekNum: number = 0;
constructor(private datePipe: DatePipe) { }
calcWeekOfTheYear(dateInput: Date) {
let falseWeekNum = parseInt(this.datePipe.transform(dateInput, 'ww'));
this.rightWeekNum = (dateInput.getDay() == 0) ? falseWeekNumber-1 : falseWeekNumber;
}
Inspired from RobG's answer.
What I wanted is the day of the week of a given date. So my answer is simply based on the day of the week Sunday. But you can choose the other day (i.e. Monday, Tuesday...);
First I find the Sunday in a given date and then calculate the week.
function getStartWeekDate(d = null) {
const now = d || new Date();
now.setHours(0, 0, 0, 0);
const sunday = new Date(now);
sunday.setDate(sunday.getDate() - sunday.getDay());
return sunday;
}
function getWeek(date) {
const sunday = getStartWeekDate(date);
const yearStart = new Date(Date.UTC(2021, 0, 1));
const weekNo = Math.ceil((((sunday - yearStart) / 86400000) + 1) / 7);
return weekNo;
}
// tests
for (let i = 0; i < 7; i++) {
let m = 14 + i;
let x = getWeek(new Date(2021, 2, m));
console.log('week num: ' + x, x + ' == ' + 11, x == 11, m);
}
for (let i = 0; i < 7; i++) {
let m = 21 + i;
let x = getWeek(new Date(2021, 2, m));
console.log('week num: ' + x, x + ' == ' + 12, x == 12, 'date day: ' + m);
}
for (let i = 0; i < 4; i++) {
let m = 28 + i;
let x = getWeek(new Date(2021, 2, m));
console.log('week num: ' + x, x + ' == ' + 13, x == 13, 'date day: ' + m);
}
for (let i = 0; i < 3; i++) {
let m = 1 + i;
let x = getWeek(new Date(2021, 3, m));
console.log('week num: ' + x, x + ' == ' + 13, x == 13, 'date day: ' + m);
}
for (let i = 0; i < 7; i++) {
let m = 4 + i;
let x = getWeek(new Date(2021, 3, m));
console.log('week num: ' + x, x + ' == ' + 14, x == 14, 'date day: ' + m);
}
now = new Date();
today = new Date(now.getFullYear(), now.getMonth(), now.getDate());
firstOfYear = new Date(now.getFullYear(), 0, 1);
numOfWeek = Math.ceil((((today - firstOfYear) / 86400000)-1)/7);
function getWeek(param) {
let onejan = new Date(param.getFullYear(), 0, 1);
return Math.ceil((((param.getTime() - onejan.getTime()) / 86400000) + onejan.getDay()) / 7);
}

JavaScript calculate the day of the year (1 - 366)

How do I use JavaScript to calculate the day of the year, from 1 - 366?
For example:
January 3 should be 3.
February 1 should be 32.
Following OP's edit:
var now = new Date();
var start = new Date(now.getFullYear(), 0, 0);
var diff = now - start;
var oneDay = 1000 * 60 * 60 * 24;
var day = Math.floor(diff / oneDay);
console.log('Day of year: ' + day);
Edit: The code above will fail when now is a date in between march 26th and October 29th andnow's time is before 1AM (eg 00:59:59). This is due to the code not taking daylight savings time into account. You should compensate for this:
var now = new Date();
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);
console.log('Day of year: ' + day);
I find it very interesting that no one considered using UTC since it is not subject to DST. Therefore, I propose the following:
function daysIntoYear(date){
return (Date.UTC(date.getFullYear(), date.getMonth(), date.getDate()) - Date.UTC(date.getFullYear(), 0, 0)) / 24 / 60 / 60 / 1000;
}
You can test it with the following:
[new Date(2016,0,1), new Date(2016,1,1), new Date(2016,2,1), new Date(2016,5,1), new Date(2016,11,31)]
.forEach(d =>
console.log(`${d.toLocaleDateString()} is ${daysIntoYear(d)} days into the year`));
Which outputs for the leap year 2016 (verified using http://www.epochconverter.com/days/2016):
1/1/2016 is 1 days into the year
2/1/2016 is 32 days into the year
3/1/2016 is 61 days into the year
6/1/2016 is 153 days into the year
12/31/2016 is 366 days into the year
This works across Daylight Savings Time changes in all countries (the "noon" one above doesn't work in Australia):
Date.prototype.isLeapYear = function() {
var year = this.getFullYear();
if((year & 3) != 0) return false;
return ((year % 100) != 0 || (year % 400) == 0);
};
// Get Day of Year
Date.prototype.getDOY = function() {
var dayCount = [0, 31, 59, 90, 120, 151, 181, 212, 243, 273, 304, 334];
var mn = this.getMonth();
var dn = this.getDate();
var dayOfYear = dayCount[mn] + dn;
if(mn > 1 && this.isLeapYear()) dayOfYear++;
return dayOfYear;
};
Date.prototype.dayOfYear= function(){
var j1= new Date(this);
j1.setMonth(0, 0);
return Math.round((this-j1)/8.64e7);
}
alert(new Date().dayOfYear())
Luckily this question doesn't specify if the number of the current day is required, leaving room for this answer.
Also some answers (also on other questions) had leap-year problems or used the Date-object. Although javascript's Date object covers approximately 285616 years (100,000,000 days) on either side of January 1 1970, I was fed up with all kinds of unexpected date inconsistencies across different browsers (most notably year 0 to 99). I was also curious how to calculate it.
So I wrote a simple and above all, small algorithm to calculate the correct (Proleptic Gregorian / Astronomical / ISO 8601:2004 (clause 4.3.2.1), so year 0 exists and is a leap year and negative years are supported) day of the year based on year, month and day.
Note that in AD/BC notation, year 0 AD/BC does not exist: instead year 1 BC is the leap-year! IF you need to account for BC notation then simply subtract one year of the (otherwise positive) year-value first!!
I modified (for javascript) the short-circuit bitmask-modulo leapYear algorithm and came up with a magic number to do a bit-wise lookup of offsets (that excludes jan and feb, thus needing 10 * 3 bits (30 bits is less than 31 bits, so we can safely save another character on the bitshift instead of >>>)).
Note that neither month or day may be 0. That means that if you need this equation just for the current day (feeding it using .getMonth()) you just need to remove the -- from --m.
Note this assumes a valid date (although error-checking is just some characters more).
function dayNo(y,m,d){
return --m*31-(m>1?(1054267675>>m*3-6&7)-(y&3||!(y%25)&&y&15?0:1):0)+d;
}
<!-- some examples for the snippet -->
<input type=text value="(-)Y-M-D" onblur="
var d=this.value.match(/(-?\d+)[^\d]+(\d\d?)[^\d]+(\d\d?)/)||[];
this.nextSibling.innerHTML=' Day: ' + dayNo(+d[1], +d[2], +d[3]);
" /><span></span>
<br><hr><br>
<button onclick="
var d=new Date();
this.nextSibling.innerHTML=dayNo(d.getFullYear(), d.getMonth()+1, d.getDate()) + ' Day(s)';
">get current dayno:</button><span></span>
Here is the version with correct range-validation.
function dayNo(y,m,d){
return --m>=0 && m<12 && d>0 && d<29+(
4*(y=y&3||!(y%25)&&y&15?0:1)+15662003>>m*2&3
) && m*31-(m>1?(1054267675>>m*3-6&7)-y:0)+d;
}
<!-- some examples for the snippet -->
<input type=text value="(-)Y-M-D" onblur="
var d=this.value.match(/(-?\d+)[^\d]+(\d\d?)[^\d]+(\d\d?)/)||[];
this.nextSibling.innerHTML=' Day: ' + dayNo(+d[1], +d[2], +d[3]);
" /><span></span>
Again, one line, but I split it into 3 lines for readability (and following explanation).
The last line is identical to the function above, however the (identical) leapYear algorithm is moved to a previous short-circuit section (before the day-number calculation), because it is also needed to know how much days a month has in a given (leap) year.
The middle line calculates the correct offset number (for max number of days) for a given month in a given (leap)year using another magic number: since 31-28=3 and 3 is just 2 bits, then 12*2=24 bits, we can store all 12 months. Since addition can be faster then subtraction, we add the offset (instead of subtract it from 31). To avoid a leap-year decision-branch for February, we modify that magic lookup-number on the fly.
That leaves us with the (pretty obvious) first line: it checks that month and date are within valid bounds and ensures us with a false return value on range error (note that this function also should not be able to return 0, because 1 jan 0000 is still day 1.), providing easy error-checking: if(r=dayNo(/*y, m, d*/)){}.
If used this way (where month and day may not be 0), then one can change --m>=0 && m<12 to m>0 && --m<12 (saving another char).
The reason I typed the snippet in it's current form is that for 0-based month values, one just needs to remove the -- from --m.
Extra:
Note, don't use this day's per month algorithm if you need just max day's per month. In that case there is a more efficient algorithm (because we only need leepYear when the month is February) I posted as answer this question: What is the best way to determine the number of days in a month with javascript?.
If used moment.js, we can get or even set the day of the year.
moment().dayOfYear();
//for getting
moment().dayOfYear(Number);
//for setting
moment.js is using this code for day of year calculation
If you don't want to re-invent the wheel, you can use the excellent date-fns (node.js) library:
var getDayOfYear = require('date-fns/get_day_of_year')
var dayOfYear = getDayOfYear(new Date(2017, 1, 1)) // 1st february => 32
This is my solution:
Math.floor((Date.now() - new Date(new Date().getFullYear(), 0, 0)) / 86400000)
Demo:
const getDateOfYear = (date) =>
Math.floor((date.getTime() - new Date(date.getFullYear(), 0, 0)) / 864e5);
const dayOfYear = getDateOfYear(new Date());
console.log(dayOfYear);
const dayOfYear = date => {
const myDate = new Date(date);
const year = myDate.getFullYear();
const firstJan = new Date(year, 0, 1);
const differenceInMillieSeconds = myDate - firstJan;
return (differenceInMillieSeconds / (1000 * 60 * 60 * 24) + 1);
};
const result = dayOfYear("2019-2-01");
console.log(result);
Well, if I understand you correctly, you want 366 on a leap year, 365 otherwise, right? A year is a leap year if it's evenly divisible by 4 but not by 100 unless it's also divisible by 400:
function daysInYear(year) {
if(year % 4 === 0 && (year % 100 !== 0 || year % 400 === 0)) {
// Leap year
return 366;
} else {
// Not a leap year
return 365;
}
}
Edit after update:
In that case, I don't think there's a built-in method; you'll need to do this:
function daysInFebruary(year) {
if(year % 4 === 0 && (year % 100 !== 0 || year % 400 === 0)) {
// Leap year
return 29;
} else {
// Not a leap year
return 28;
}
}
function dateToDay(date) {
var feb = daysInFebruary(date.getFullYear());
var aggregateMonths = [0, // January
31, // February
31 + feb, // March
31 + feb + 31, // April
31 + feb + 31 + 30, // May
31 + feb + 31 + 30 + 31, // June
31 + feb + 31 + 30 + 31 + 30, // July
31 + feb + 31 + 30 + 31 + 30 + 31, // August
31 + feb + 31 + 30 + 31 + 30 + 31 + 31, // September
31 + feb + 31 + 30 + 31 + 30 + 31 + 31 + 30, // October
31 + feb + 31 + 30 + 31 + 30 + 31 + 31 + 30 + 31, // November
31 + feb + 31 + 30 + 31 + 30 + 31 + 31 + 30 + 31 + 30, // December
];
return aggregateMonths[date.getMonth()] + date.getDate();
}
(Yes, I actually did that without copying or pasting. If there's an easy way I'll be mad)
This is a simple way to find the current day in the year, and it should account for leap years without a problem:
Javascript:
Math.round((new Date().setHours(23) - new Date(new Date().getYear()+1900, 0, 1, 0, 0, 0))/1000/60/60/24);
Javascript in Google Apps Script:
Math.round((new Date().setHours(23) - new Date(new Date().getYear(), 0, 1, 0, 0, 0))/1000/60/60/24);
The primary action of this code is to find the number of milliseconds that have elapsed in the current year and then convert this number into days. The number of milliseconds that have elapsed in the current year can be found by subtracting the number of milliseconds of the first second of the first day of the current year, which is obtained with new Date(new Date().getYear()+1900, 0, 1, 0, 0, 0) (Javascript) or new Date(new Date().getYear(), 0, 1, 0, 0, 0) (Google Apps Script), from the milliseconds of the 23rd hour of the current day, which was found with new Date().setHours(23). The purpose of setting the current date to the 23rd hour is to ensure that the day of year is rounded correctly by Math.round().
Once you have the number of milliseconds of the current year, then you can convert this time into days by dividing by 1000 to convert milliseconds to seconds, then dividing by 60 to convert seconds to minutes, then dividing by 60 to convert minutes to hours, and finally dividing by 24 to convert hours to days.
Note: This post was edited to account for differences between JavaScript and JavaScript implemented in Google Apps Script. Also, more context was added for the answer.
I think this is more straightforward:
var date365 = 0;
var currentDate = new Date();
var currentYear = currentDate.getFullYear();
var currentMonth = currentDate.getMonth();
var currentDay = currentDate.getDate();
var monthLength = [31,28,31,30,31,30,31,31,30,31,30,31];
var leapYear = new Date(currentYear, 1, 29);
if (leapYear.getDate() == 29) { // If it's a leap year, changes 28 to 29
monthLength[1] = 29;
}
for ( i=0; i < currentMonth; i++ ) {
date365 = date365 + monthLength[i];
}
date365 = date365 + currentDay; // Done!
This method takes into account timezone issue and daylight saving time
function dayofyear(d) { // d is a Date object
var yn = d.getFullYear();
var mn = d.getMonth();
var dn = d.getDate();
var d1 = new Date(yn,0,1,12,0,0); // noon on Jan. 1
var d2 = new Date(yn,mn,dn,12,0,0); // noon on input date
var ddiff = Math.round((d2-d1)/864e5);
return ddiff+1;
}
(took from here)
See also this fiddle
Math.round((new Date().setHours(23) - new Date(new Date().getFullYear(), 0, 1, 0, 0, 0))/1000/86400);
further optimizes the answer.
Moreover, by changing setHours(23) or the last-but-two zero later on to another value may provide day-of-year related to another timezone.
For example, to retrieve from Europe a resource located in America.
This might be useful to those who need the day of the year as a string and have jQuery UI available.
You can use jQuery UI Datepicker:
day_of_year_string = $.datepicker.formatDate("o", new Date())
Underneath it works the same way as some of the answers already mentioned ((date_ms - first_date_of_year_ms) / ms_per_day):
function getDayOfTheYearFromDate(d) {
return Math.round((new Date(d.getFullYear(), d.getMonth(), d.getDate()).getTime()
- new Date(d.getFullYear(), 0, 0).getTime()) / 86400000);
}
day_of_year_int = getDayOfTheYearFromDate(new Date())
maybe help anybody
let day = (date => {
return Math.floor((date - new Date(date.getFullYear(), 0, 0)) / 1000 / 60 / 60 / 24)
})(new Date())
I've made one that's readable and will do the trick very quickly, as well as handle JS Date objects with disparate time zones.
I've included quite a few test cases for time zones, DST, leap seconds and Leap years.
P.S. ECMA-262 ignores leap seconds, unlike UTC. If you were to convert this to a language that uses real UTC, you could just add 1 to oneDay.
// returns 1 - 366
findDayOfYear = function (date) {
var oneDay = 1000 * 60 * 60 * 24; // A day in milliseconds
var og = { // Saving original data
ts: date.getTime(),
dom: date.getDate(), // We don't need to save hours/minutes because DST is never at 12am.
month: date.getMonth()
}
date.setDate(1); // Sets Date of the Month to the 1st.
date.setMonth(0); // Months are zero based in JS's Date object
var start_ts = date.getTime(); // New Year's Midnight JS Timestamp
var diff = og.ts - start_ts;
date.setDate(og.dom); // Revert back to original date object
date.setMonth(og.month); // This method does preserve timezone
return Math.round(diff / oneDay) + 1; // Deals with DST globally. Ceil fails in Australia. Floor Fails in US.
}
// Tests
var pre_start_dst = new Date(2016, 2, 12);
var on_start_dst = new Date(2016, 2, 13);
var post_start_dst = new Date(2016, 2, 14);
var pre_end_dst_date = new Date(2016, 10, 5);
var on_end_dst_date = new Date(2016, 10, 6);
var post_end_dst_date = new Date(2016, 10, 7);
var pre_leap_second = new Date(2015, 5, 29);
var on_leap_second = new Date(2015, 5, 30);
var post_leap_second = new Date(2015, 6, 1);
// 2012 was a leap year with a leap second in june 30th
var leap_second_december31_premidnight = new Date(2012, 11, 31, 23, 59, 59, 999);
var january1 = new Date(2016, 0, 1);
var january31 = new Date(2016, 0, 31);
var december31 = new Date(2015, 11, 31);
var leap_december31 = new Date(2016, 11, 31);
alert( ""
+ "\nPre Start DST: " + findDayOfYear(pre_start_dst) + " === 72"
+ "\nOn Start DST: " + findDayOfYear(on_start_dst) + " === 73"
+ "\nPost Start DST: " + findDayOfYear(post_start_dst) + " === 74"
+ "\nPre Leap Second: " + findDayOfYear(pre_leap_second) + " === 180"
+ "\nOn Leap Second: " + findDayOfYear(on_leap_second) + " === 181"
+ "\nPost Leap Second: " + findDayOfYear(post_leap_second) + " === 182"
+ "\nPre End DST: " + findDayOfYear(pre_end_dst_date) + " === 310"
+ "\nOn End DST: " + findDayOfYear(on_end_dst_date) + " === 311"
+ "\nPost End DST: " + findDayOfYear(post_end_dst_date) + " === 312"
+ "\nJanuary 1st: " + findDayOfYear(january1) + " === 1"
+ "\nJanuary 31st: " + findDayOfYear(january31) + " === 31"
+ "\nNormal December 31st: " + findDayOfYear(december31) + " === 365"
+ "\nLeap December 31st: " + findDayOfYear(leap_december31) + " === 366"
+ "\nLast Second of Double Leap: " + findDayOfYear(leap_second_december31_premidnight) + " === 366"
);
I would like to provide a solution that does calculations adding the days for each previous month:
function getDayOfYear(date) {
var month = date.getMonth();
var year = date.getFullYear();
var days = date.getDate();
for (var i = 0; i < month; i++) {
days += new Date(year, i+1, 0).getDate();
}
return days;
}
var input = new Date(2017, 7, 5);
console.log(input);
console.log(getDayOfYear(input));
This way you don't have to manage the details of leap years and daylight saving.
A alternative using UTC timestamps. Also as others noted the day indicating 1st a month is 1 rather than 0. The month starts at 0 however.
var now = Date.now();
var year = new Date().getUTCFullYear();
var year_start = Date.UTC(year, 0, 1);
var day_length_in_ms = 1000*60*60*24;
var day_number = Math.floor((now - year_start)/day_length_in_ms)
console.log("Day of year " + day_number);
You can pass parameter as date number in setDate function:
var targetDate = new Date();
targetDate.setDate(1);
// Now we can see the expected date as: Mon Jan 01 2018 01:43:24
console.log(targetDate);
targetDate.setDate(365);
// You can see: Mon Dec 31 2018 01:44:47
console.log(targetDate)
For those among us who want a fast alternative solution.
(function(){"use strict";
function daysIntoTheYear(dateInput){
var fullYear = dateInput.getFullYear()|0;
// "Leap Years are any year that can be exactly divided by 4 (2012, 2016, etc)
// except if it can be exactly divided by 100, then it isn't (2100, 2200, etc)
// except if it can be exactly divided by 400, then it is (2000, 2400)"
// (https://www.mathsisfun.com/leap-years.html).
var isLeapYear = ((fullYear & 3) | (fullYear/100 & 3)) === 0 ? 1 : 0;
// (fullYear & 3) = (fullYear % 4), but faster
//Alternative:var isLeapYear=(new Date(currentYear,1,29,12)).getDate()===29?1:0
var fullMonth = dateInput.getMonth()|0;
return ((
// Calculate the day of the year in the Gregorian calendar
// The code below works based upon the facts of signed right shifts
// • (x) >> n: shifts n and fills in the n highest bits with 0s
// • (-x) >> n: shifts n and fills in the n highest bits with 1s
// (This assumes that x is a positive integer)
(31 & ((-fullMonth) >> 4)) + // January // (-11)>>4 = -1
((28 + isLeapYear) & ((1-fullMonth) >> 4)) + // February
(31 & ((2-fullMonth) >> 4)) + // March
(30 & ((3-fullMonth) >> 4)) + // April
(31 & ((4-fullMonth) >> 4)) + // May
(30 & ((5-fullMonth) >> 4)) + // June
(31 & ((6-fullMonth) >> 4)) + // July
(31 & ((7-fullMonth) >> 4)) + // August
(30 & ((8-fullMonth) >> 4)) + // September
(31 & ((9-fullMonth) >> 4)) + // October
(30 & ((10-fullMonth) >> 4)) + // November
// There are no months past December: the year rolls into the next.
// Thus, fullMonth is 0-based, so it will never be 12 in Javascript
(dateInput.getDate()|0) // get day of the month
)&0xffff);
}
// Demonstration:
var date = new Date(2100, 0, 1)
for (var i=0; i<12; i=i+1|0, date.setMonth(date.getMonth()+1|0))
console.log(date.getMonth()+":\tday "+daysIntoTheYear(date)+"\t"+date);
date = new Date(1900, 0, 1);
for (var i=0; i<12; i=i+1|0, date.setMonth(date.getMonth()+1|0))
console.log(date.getMonth()+":\tday "+daysIntoTheYear(date)+"\t"+date);
// Performance Benchmark:
console.time("Speed of processing 65536 dates");
for (var i=0,month=date.getMonth()|0; i<65536; i=i+1|0)
date.setMonth(month=month+1+(daysIntoTheYear(date)|0)|0);
console.timeEnd("Speed of processing 65536 dates");
})();
The size of the months of the year and the way that Leap Years work fits perfectly into keeping our time on track with the sun. Heck, it works so perfectly that all we ever do is just adjust mere seconds here and there. Our current system of leap years has been in effect since February 24th, 1582, and will likely stay in effect for the foreseeable future.
DST, however, is very subject to change. It may be that 20 years from now, some country may offset time by a whole day or some other extreme for DST. A whole DST day will almost certainly never happen, but DST is still nevertheless very up-in-the-air and indecisive. Thus, the above solution is future proof in addition to being very very fast.
The above code snippet runs very fast. My computer can process 65536 dates in ~52ms on Chrome.
This is a solution that avoids the troublesome Date object and timezone issues, it requires that your input date be in the format "yyyy-dd-mm". If you want to change the format, then modify date_str_to_parts function:
function get_day_of_year(str_date){
var date_parts = date_str_to_parts(str_date);
var is_leap = (date_parts.year%4)==0;
var acct_for_leap = (is_leap && date_parts.month>2);
var day_of_year = 0;
var ary_months = [
0,
31, //jan
28, //feb(non leap)
31, //march
30, //april
31, //may
30, //june
31, //july
31, //aug
30, //sep
31, //oct
30, //nov
31 //dec
];
for(var i=1; i < date_parts.month; i++){
day_of_year += ary_months[i];
}
day_of_year += date_parts.date;
if( acct_for_leap ) day_of_year+=1;
return day_of_year;
}
function date_str_to_parts(str_date){
return {
"year":parseInt(str_date.substr(0,4),10),
"month":parseInt(str_date.substr(5,2),10),
"date":parseInt(str_date.substr(8,2),10)
}
}
A straightforward solution with complete explanation.
var dayOfYear = function(date) {
const daysInMonth = [31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31];
const [yyyy, mm, dd] = date.split('-').map(Number);
// Checks if February has 29 days
const isLeap = (year) => new Date(year, 1, 29).getDate() === 29;
// If it's a leap year, changes 28 to 29
if (isLeap(yyyy)) daysInMonth[1] = 29;
let daysBeforeMonth = 0;
// Slice the array and exclude the current Month
for (const i of daysInMonth.slice(0, mm - 1)) {
daysBeforeMonth += i;
}
return daysBeforeMonth + dd;
};
console.log(dayOfYear('2020-1-3'));
console.log(dayOfYear('2020-2-1'));
I wrote these two javascript functions which return the day of the year (Jan 1 = 1).
Both of them account for leap years.
function dayOfTheYear() {
// for today
var M=[31,28,31,30,31,30,31,31,30,31,30,31]; var x=new Date(); var m=x.getMonth();
var y=x.getFullYear(); if (y % 400 == 0 || (y % 4 == 0 && y % 100 != 0)) {++M[1];}
var Y=0; for (var i=0;i<m;++i) {Y+=M[i];}
return Y+x.getDate();
}
function dayOfTheYear2(m,d,y) {
// for any day : m is 1 to 12, d is 1 to 31, y is a 4-digit year
var m,d,y; var M=[31,28,31,30,31,30,31,31,30,31,30,31];
if (y % 400 == 0 || (y % 4 == 0 && y % 100 != 0)) {++M[1];}
var Y=0; for (var i=0;i<m-1;++i) {Y+=M[i];}
return Y+d;
}
One Line:
Array.from(new Array(new Date().getMonth()), (x, i) => i).reduce((c, p, idx, array)=>{
let returnValue = c + new Date(new Date().getFullYear(), p, 0).getDate();
if(idx == array.length -1){
returnValue = returnValue + new Date().getDate();
}
return returnValue;
}, 0)
I needed a reliable (leap year and time zone resistant) algorithm for an application that makes heavy use of this feature, I found some algorithm written in the 90s and found that there is still no such efficient and stable solution here:
function dayOfYear1 (date) {
const year = date.getFullYear();
const month = date.getMonth()+1;
const day = date.getDate();
const N1 = Math.floor(275 * month / 9);
const N2 = Math.floor((month + 9) / 12);
const N3 = (1 + Math.floor((year - 4 * Math.floor(year / 4) + 2) / 3));
const N = N1 - (N2 * N3) + day - 30;
return N;
}
Algorithm works correctly in leap years, it does not depend on time zones with Date() and on top of that it is more efficient than any of the lower ones:
function dayOfYear2 (date) {
const monthsDays = [0, 31, 59, 90, 120, 151, 181, 212, 243, 273, 304, 334];
const year = date.getFullYear();
const month = date.getMonth();
const day = date.getDate();
let N = monthsDays[month] + day;
if ( month>1 && year%4==0 )
N++;
return N;
}
function dayOfYear3 (date) {
const yearDate = new Date(date.getFullYear(), 0, 0);
const timeZoneDiff = yearDate.getTimezoneOffset() - date.getTimezoneOffset();
const N = Math.floor(((date - yearDate )/1000/60 + timeZoneDiff)/60/24);
return N;
}
All of them are correct and work under the conditions mentioned above.
Performance comparison in 100k loop:
dayOfYear1 - 15 ms
dayOfYear2 - 17 ms
dayOfYear3 - 80 ms
It always get's me worried when mixing maths with date functions (it's so easy to miss some leap year other detail). Say you have:
var d = new Date();
I would suggest using the following, days will be saved in day:
for(var day = d.getDate(); d.getMonth(); day += d.getDate())
d.setDate(0);
Can't see any reason why this wouldn't work just fine (and I wouldn't be so worried about the few iterations since this will not be used so intensively).

Categories

Resources