Determining time elapsed between 2 dates - javascript

I am trying to determine the time elapsed between 2 dates using javascript. An example would be: "I quit smoking on January 5, 2008 at 3 A.M., how many years, months, and hours has elapsed since I quit?".
So my thoughts were:
Get "quit" date
Get current date
Convert to time (milliseconds)
Find the difference
Create a new date using the difference
Extract the years, months, etc. from that date
Well, it is acting strange and I can't pin point why. Any insight?
//create custom test date
var d1 = new Date(2012, 8, 28, 13, 14, 0, 0);
//create current date
var d2 = new Date();
//get date times (ms)
var d1Time = (d1.getTime());
var d2Time = (d2.getTime());
//calculate the difference in date times
var diff = d2 - d1;
//create a new date using the time differences (starts at Jan 1, 1970)
var dDiff = new Date();
dDiff.setTime(diff);
//chop off 1970 and get year, month, day, and hour
var years = dDiff.getFullYear() - 1970;
var months = dDiff.getMonth();
var days = dDiff.getDate();
var hours = dDiff.getHours();
You can see it in action at this temporary host.

Why don't you just do the math to calculate the values? What you are putting into Date when you do dDiff.setTime(diff); is meaningless to you. That is just going to give you the date diff ms from the epoch.

Changing part of your code may solve your problem. jsfiddle
var start = new Date(0); // pivote point of date.
var years = dDiff.getFullYear() - start.getFullYear();
var months = dDiff.getMonth() - start.getMonth();
var days = dDiff.getDate() - start.getDate();
var hours = dDiff.getHours() - start.getHours();;
console.log(years, months, days, hours);​
But you have to manipulate these values based on there value( they may come negative).

Date represents a particular point in time, not a timespan between two dates.
You are creating a new date by setting dDiff milliseconds ellapsed since the unix epoch.
Once you have the milliseconds ellapsed, you should extract the information you need by dividing it. See this question.
May I recomend taking a look at Moment.js?

This won't be accurate as it does not take into account the leap dayys. Other than that, it is working correctly and I don't see any problem. The time difference is roughly 6.5 days. Taking into account timezone and the fact that 0 is Jan 1st, the value I see is as expected.
The accurate solution would be to
Convert the time difference into days
Subtract the number of leap years elapsed since the specified date
Divide the remaining by 365 to get the number of days
Create an array with the day count of each month (without considering leap days) and loop through the elapsed months, subtracting the day count for the completed months. The number of iterations will be your month count
The remainder is your day count

Various notes:
new Date(2012, 8, 28, 13, 14, 0, 0); is 28 September 2012 13:14:00 (not August if you would it)
new Date(0) returned value is not a constant, because of the practice of using Daylight Saving Time.
dDiff.getMonth(); return 0 for Jan, 1 for Feb etc.
The begin of date (1 Jan 1970) begin with 1 so in difference you should subtract this.
I think the second point is your mistake.
According with your algorithm, try this:
// create date in UTC
//create custom test date
var dlocaltime = new Date(2012, 8, 28, 13, 14, 0, 0);
var d1 = new Date(dlocaltime.getUTCFullYear(),dlocaltime.getUTCMonth(), dlocaltime.getUTCDate(), dlocaltime.getUTCHours(),dlocaltime.getUTCMinutes(),dlocaltime.getUTCSeconds());
//create current date
var now = new Date();
var d2 = new Date(now.getUTCFullYear(), now.getUTCMonth(), now.getUTCDate(), now.getUTCHours(), now.getUTCMinutes(), now.getUTCSeconds());
console.log(d1);
console.log(d2);
//get date times (ms)
var d1Time = (d1.getTime());
var d2Time = (d2.getTime());
//calculate the difference in date times
var diff = d2 - d1;
//create a new date using the time differences (starts at Jan 1, 1970)
var dDiff = new Date();
dDiff.setTime(diff);
//chop off 1970 and get year, month, day, and hour
var years = dDiff.getUTCFullYear() - 1970;
var months = dDiff.getUTCMonth();
var days = dDiff.getUTCDate()-1; // the date of new Date(0) begin with 1
var hours = dDiff.getUTCHours();
var minutes = dDiff.getUTCMinutes();
var seconds = dDiff.getUTCSeconds();
console.log("Years:"+years);
console.log("months:"+months);
console.log("days:"+days);
console.log("hours:"+hours);
console.log("minutes:"+minutes);
console.log("seconds:"+seconds);

Related

Date calculation using javaScript

I need date algorithms, Which will display me how long I have been given a date anywhere.
Example:
Suppose
Today is 01/06/2019 (dd/mm/yy)
BirthDate is 31/05/2019 (dd/mm/yy)
Now, My age is 1 day 0 Months and 0 years
[NOTE: I need all of them, It means day/month and years]
I have been read at least 23 articles/post in this site but they only give years or month or date but not everything in one...
var date, cDate, cMonth, cYears, oDate, oMonth, oYears;
date = new Date()
//current date
cDate = date.getDate()
cMonth = date.getMonth()
cYears = date.getFullYear()
//birth date
oDate = 01
oMonth = 05
oYears = 2019
(Multiplying is not the main solution I think so, need to work with all arithmetics operator)
This will give you the result you need
var birth = new Date("5/31/2019"); // mm/dd/year
var today = new Date();
var diff = today.valueOf()-birth.valueOf();
var result = new Date(diff);
var dayDiff = result.getDate() - 1; //because epoch start from 1st
var yearDiff = result.getFullYear() - 1970; //because epoch start from 1970
var str = `${dayDiff} day ${result.getMonth()} Months and ${yearDiff} years`;
console.log(str);
You should use moment, so there you can do:
var a = moment("04/09/2019 15:00:00");
var b = moment("04/09/2013 14:20:30");
console.log(a.diff(b, 'years'))
console.log(a.diff(b, 'months'))
console.log(a.diff(b, 'days'))
Similarly, you can get minutes, hours and seconds if you need.
While using the library moment.js

Javascript, counting years and days since 1970-01-01 until today

I'm trying to count the numbers of years and the days(that remains after the years is counted). So it shows how long its gone in years+days since 1970-01-01. Right now I'm only able to get the years right, and I'm not sure if the days are correct. They are both separated, I need them to in some way make var diffDays and diffYear. A calculation so the computer gets that after counting years, to do minus numbers of years in days and show how many days thats left, since today.
<head>
<script>
var today = new Date();
var dd = today.getDate();
document.write(today);
function myFunction() {
var oneDay = 24*60*60*1000; // hours*minutes*seconds*milliseconds
var firstDate = new Date(1970,01,01);
var secondDate = new Date();
var diffYear = Math.round(Math.abs((firstDate.getTime() - secondDate.getTime())/(oneDay)/365));
var diffDays = Math.round(Math.abs((firstDate.getTime() - secondDate.getTime())/(oneDay)));
document.getElementById("antalYear").innerHTML = diffYear;
document.getElementById("antalDagar").innerHTML = diffDays;
}
</script>
</head>
<body onload="myFunction()">
<p>
Numbers of years and days:
<h3>
<span id="antalYear"></span>
years and
<span id="antalDagar"></span>
days
</h3> Since: 1970,01,01.
</p>
</body>
If you're okay with using a library I would recommend moment.js
It's the go to for handling almost anything related to dates.
var oldDate = moment("1970-01-01", "YYYY-MM-DD")
var today = moment()
console.log(today.diff(oldDate, "years"));
console.log(today.diff(oldDate, "days"));
$(".years").append(today.diff(oldDate, "years"))
$(".days").append(today.diff(oldDate, "days"))
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.23.0/moment.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
Years:<div class="years"></div>
</br>
Days:<div class="days"></div>
For the number of years since 1970, just subtract it from the current year:
date.getFullYear() - 1970
For the number of days since the beginning of the year, you can subtract a date for 1 Jan in the current year from the current date to get milliseconds, then divide by ms per day. However, that doesn't allow for daylight saving changeovers which might affect the result. If you want to round up, so that any time on 1 January is 1 day, etc. then you can set the time to 12 noon, divide by ms/day and round up (or round down and add one). That gives you the day number of the year.
E.g.
function dayOfYear(date) {
// Copy date so don't affect original
var d = new Date(date);
// Get time value for start of 1 Jan in date year
var yearStart = new Date(d.getFullYear(), 0);
// Get number of days, rounded up
return Math.ceil((d.setHours(12,0,0,0) - yearStart) / 8.64e7);
}
// Day of year for current date
console.log('Current day number: ' + dayOfYear(new Date()));
// Day of year for 31 Dec 2016
console.log('Day number for 31 Dec 2016: ' + dayOfYear(new Date(2016, 11, 31))); // 366
If you want the number of completed days (so 1 Jan is 0, 2 Jan is 1, etc.) just subtract 1 from the result (or use Math.floor instead of Math.ceil).

Pikaday date range don't work

I used the range function from pikaday.
with onSelectI set the date range what actually works.
Here is my example:
onSelect: function(date) {
var first_ = (date.getDate() - date.getDay())+1;
var last_ = first_ + 4;
var firstday = new Date(date.setDate(first_));
var lastday = new Date(date.setDate(last_));
picker.setStartRange(firstday);
picker.setEndRange(lastday);
picker.draw();
var f_startdate = firstday.getDate()+'.'+(firstday.getMonth()+1)+'.'+firstday.getFullYear();
var f_enddate = lastday.getDate()+'.'+(lastday.getMonth()+1)+'.'+lastday.getFullYear();
var kw = getWeekNumber(date.getFullYear()+'/'+(date.getMonth()+1)+'/'+date.getDate());
document.getElementById('calendar').value = f_startdate+' - '+f_enddate;
// document.getElementById('calendar').value = 'KW: '+(kw+1);
}
But when I select the 03.06.2016 the range is set to the "30.05.2016 - 03.05.2016" and the Input is wrong. Maybe anyone can help me.
Here is a working example: https://jsfiddle.net/24aL9f21/1/
Your issue is here:
var first_ = (date.getDate() - date.getDay())+1;
That gives you the date of the previous Monday, but also goes negative. 3 June is a Friday (day number 5), so first_ is set to:
3 - 5 + 1 = -1
Then:
var last_ = first_ + 4;
so last_ is set to 3. Now when you do:
var firstday = new Date(date.setDate(first_));
you are actually setting date to a date of -1, which is one before the start of the month so 30 May. setDate returns the time value, so firstday is a new Date instance set to 30 May also.
Then:
var lastday = new Date(date.setDate(last_));
you are setting date to 3 May (remembering that in the line above you set it to 30 May). Again, the setDate method returns the time value, so a new Date object is created for that date. So you get dates for 30 May and 3 May (and if you check date, you'll set it's also 3 May).
QED (which my Mathematics teacher told me was "Quite Easily Done"). ;-)
So your code for the Monday is fine. If you want to get the date for the following Friday, just do:
var lastday = date.setDate(date.getDate() + 4);
Here lastday and date will reference the same Date object, but creating another copy doesn't seem useful.

Setting Javascript Date in future

I'm editing a countdown clock but unsure how to set the future date in javascript. The example set's it for the next New Years. I need to set it as a fixed date, 27th April 2015.
// Grab the current date
var currentDate = new Date();
// Set some date in the future. In this case, it's always Jan 1
var futureDate = new Date(currentDate.getFullYear() + 1, 0, 1);
// Calculate the difference in seconds between the future and current date
var diff = futureDate.getTime() / 1000 - currentDate.getTime() / 1000;
I'm just unsure how to set the future date correctly to be the 27 April 2015.
Thanks!
Matt
var d = new Date();
d.setDate(27);
d.setMonth(3);
d.setYear(2015);
console.log(d);
This is how you add days to a date:
var currentDate = new Date();
futureDate.setDate(currentDate.getDate() + 10 /* 10 days */ );
Did you just want to set it to April 27th of the next year? If so this should work.
var futureDate = new Date(currentDate.getFullYear() + 1, 3, 27);
Working JS Fiddle:
http://jsfiddle.net/Kitchenfinks/xukwLbdk/

Javascript repeating days counter

I need a JavaScript function that returns the number of days remaining from a particular date of every year.
I found the following code, but how can I make it repeatable for every year, instead of changing the year in the function manually?
function daysUntil(year, month, day) {
var now = new Date(),
dateEnd = new Date(year, month - 1, day), // months are zero-based
days = (dateEnd - now) / 1000/60/60/24; // convert milliseconds to days
return Math.round(days);
}
daysUntil(2013, 10, 26);
I think my question above is not clear enough, i need to show days remaining in 26th October. So this starts again every year on 27th October. I don't need a loop for that.
"how can i make it repeatable for every year, instead of changing the year in function manually?"
Well you can't do literally every year to infinity, but you can easily add a loop to get a specific range of years:
var d;
for (var y = 2013; y < 2099; y++) {
d = daysUntil(y, 10, 26);
// do something with d, e.g.,
console.log(d);
}
UPDATE: You added this detail to your question:
"I think my question above is not clear enough, i need to show days remaining in 26th October. So this starts again every year on 27th October. I don't need a loop for that."
OK, that's still not very clear, but I think you're saying that your input would be just the day and month and you want to calculate the number of days until the next time that day/month rolls around, e.g., the number of days until your next birthday. If so, perhaps something like this:
function daysUntil(month, day) {
var now = new Date(),
currentYear = now.getFullYear(),
dateEnd = new Date(currentYear, month - 1, day); // months are zero-based
if (dateEnd - now < 0) // have we already passed that date this year?
dateEnd.setFullYear(currentYear + 1);
return Math.ceil((dateEnd - now) / 1000/60/60/24);
}
console.log(daysUntil(10,11)); // 365 - results from today, Oct 11
console.log(daysUntil(10,26)); // 15
console.log(daysUntil(7,7)); // 269

Categories