This question already has answers here:
Difference between two dates in years, months, days in JavaScript
(34 answers)
Closed 8 years ago.
I am trying to make a website that tells you (in years, months, weeks, hours, minutes and seconds) how old you are. I have got all of them working apart from months and years. Once I get the months I will be able to get the years (hopefully), however I'm having trouble thinking of a way to get the months. For the others it was easy (once I had the seconds between the birth date and the current date I could just convert seconds to minutes, to hours, to days etc.), however for months I'm going to need to take into account the fact they are all different lengths, AND leap years (which currently does not affect the days either).
Hope this helps you out
// Set the unit values in milliseconds.
var msecPerMinute = 1000 * 60;
var msecPerHour = msecPerMinute * 60;
var msecPerDay = msecPerHour * 24;
// Set a date and get the milliseconds
var date = new Date('6/15/1990');
var dateMsec = date.getTime();
// Set the date to January 1, at midnight, of the specified year.
date.setMonth(0);
date.setDate(1);
date.setHours(0, 0, 0, 0);
// Get the difference in milliseconds.
var interval = dateMsec - date.getTime();
// Calculate how many days the interval contains. Subtract that
// many days from the interval to determine the remainder.
var days = Math.floor(interval / msecPerDay );
interval = interval - (days * msecPerDay );
// Calculate the hours, minutes, and seconds.
var hours = Math.floor(interval / msecPerHour );
interval = interval - (hours * msecPerHour );
var minutes = Math.floor(interval / msecPerMinute );
interval = interval - (minutes * msecPerMinute );
var seconds = Math.floor(interval / 1000 );
// Display the result.
document.write(days + " days, " + hours + " hours, " + minutes + " minutes, " + seconds + " seconds.");
//Output: 164 days, 23 hours, 0 minutes, 0 seconds.
Would you consider an external library? Check out http://momentjs.com/
You can easily do something like
date1.diff(date2, 'months')
Related
I am trying to compare 2 dates and represent the difference( converted to miliseconds) via years,months,days,minutes and seconds.I am new in JS,I looked up for a ready method to convert miliseconds to years,months,days, minutes, seconds but didn't find.Tell me please is there such method? If not how can I do that? Simply by dividing the difference and using reminder?Thank you in advance for help.
Without having a calendar and knowing the input dates, the best you can do is be approximate.
Here is a script that shows the time elapsed since midnight last night.
var diff = Date.now() - Date.parse("July 13, 2016");
var seconds = Math.floor(diff / 1000),
minutes = Math.floor(seconds / 60),
hours = Math.floor(minutes / 60),
days = Math.floor(hours / 24),
months = Math.floor(days / 30),
years = Math.floor(days / 365);
seconds %= 60;
minutes %= 60;
hours %= 24;
days %= 30;
months %= 12;
console.log("Years:", years);
console.log("Months:", months);
console.log("Days:", days);
console.log("Hours:", hours);
console.log("Minutes:", minutes);
console.log("Seconds:", seconds);
There is no inbuilt method to convert given millisecond to equivalent seconds, minutes, hours, days, months or years.
You will have to use math. Although you will only be able to convert accurately up to days. Months and years will vary as months are either 28, 29, 30 or 31 and there are leap years.
Consider having a look at http://momentjs.com/ before you write anything on your own, as you can do a lot more with this library like adding and subtracting days or hours etc
I'm writing a function that accepts a future date and returns a string in the form "X weeks, Y days, Z hours" representing the countdown to that date. My approach is:
Get the number of seconds separating the two dates by subtracting the future date's epoch time from today's epoch time.
Divide the number of seconds by 604800 (the number of seconds in a week). Store the result as weeks, and redefine seconds as the remainder (which is what Ruby's divmod does).
Do the same thing for days, hours, and minutes.
First I wrote it in Ruby, which works:
def time_countdown(*date_string)
seconds = Time.new(*date_string).to_i - Time.now.to_i
weeks, seconds = seconds.divmod 604800
days, seconds = seconds.divmod 86400
hours, seconds = seconds.divmod 3600
minutes, seconds = seconds.divmod 60
return "#{weeks} weeks, #{days} days, #{hours} hours."
end
I translated this to JavaScript with the same approach except for the following:
Since JavaScript lacks divmod, I did that manually, first setting the weeks/days/hours and then setting seconds to the remainder.
I need to use Math.floor because JavaScript exclusively uses floats.
I divide the epoch times by 1,000 since JS uses milliseconds for its epoch timestamps unlike Ruby.
My JS function expects to receive an epochTime integer since I haven't learnt how to pass around arbitrary-length argument lists in JS.
The code is:
function timeCountdown(epochTime) {
var seconds = epochTime/1000 - new Date().getTime() / 1000;
var weeks = Math.floor(seconds / 604800);
seconds = seconds % 604800;
var days = Math.floor(seconds / 86400);
seconds = seconds % 86400;
var hours = Math.floor(seconds / 3600);
seconds = seconds % 3600;
return weeks + " weeks, " + days + " days, " + hours + " hours.";
}
For the date 2015,6,19, as of June 1st, JS gives "6 weeks, 5 days, 21 hours" and Ruby gives "2 weeks, 3 days, 6 hours". I can't figure out where this difference arises. Could someone point out my mistake?
Yet if I feed the date 2015,6,19 to both functions, it being June 1st as I write this, JS tells me 6 weeks, 5 days, 21 hours and Ruby tells me 2 wweeks, 3 days, 6 hours.
You haven't shown how you're doing that, but my guess is you're doing:
timeCountdown(new Date(2015, 6, 19));
...but in JavaScript, month numbers start with 0, not 1, so June is month 5, not 6:
timeCountdown(new Date(2015, 5, 19));
// --------------------------^
Example:
function timeCountdown(epochTime) {
var seconds = epochTime/1000 - new Date().getTime() / 1000;
var weeks = Math.floor(seconds / 604800);
seconds = seconds % 604800;
var days = Math.floor(seconds / 86400);
seconds = seconds % 86400;
var hours = Math.floor(seconds / 3600);
seconds = seconds % 3600;
return weeks + " weeks, " + days + " days, " + hours + " hours.";
}
snippet.log("July 19th: " + timeCountdown(new Date(2015, 6, 19)));
snippet.log("June 19th: " + timeCountdown(new Date(2015, 5, 19)));
<!-- Script provides the `snippet` object, see http://meta.stackexchange.com/a/242144/134069 -->
<script src="http://tjcrowder.github.io/simple-snippets-console/snippet.js"></script>
I'm trying to create a timer that counts down in years, months, days, hours, minutes, seconds and milliseconds. I've found a few guides online, but they are sort of not easy to understand, or do not do the milliseconds. Can anyone help me do something like this, say, for this friday at 13:30.
so it could read 0y 0m 2d 2h 11m 50ms
and counts down the milliseconds. I would show code to demonstrate that I have actually tried to do this myself, but it all failed so dismally that i'd be embarrassed to.
I also read this article, which makes me mistrust javascript timers a bit. Is this true, that they become so out of sync?
Thanks for any help!
Depends how you implement it.
If you read the time once and depend on the setInterval or/and setTimeout for the accuracy then yes .. they can get out of sync.
If you always get the current time for using in your calculations, then it can go out of sync like the rest of your system goes out of sync... meaning that it follows the clock of the computer.
Altering my answer at JavaScript / jQuery Countdown to add milliseconds you get
var end = new Date('13 Apr 2012 13:30:00');
var _second = 1000;
var _minute = _second * 60;
var _hour = _minute * 60;
var _day = _hour *24;
var timer;
function showRemaining()
{
var now = new Date();
var distance = end - now;
if (distance < 0 ) {
// handle expiry here..
clearInterval( timer ); // stop the timer from continuing ..
//alert('Expired'); // alert a message that the timer has expired..
}
var days = Math.floor(distance / _day);
var hours = Math.floor( (distance % _day ) / _hour );
var minutes = Math.floor( (distance % _hour) / _minute );
var seconds = Math.floor( (distance % _minute) / _second );
var milliseconds = distance % _second;
var countdownElement = document.getElementById('timer');
countdownElement.innerHTML = days + 'd ' +
hours + 'h ' +
minutes + 'm ' +
seconds + 's ' +
milliseconds + 'ms';
}
timer = setInterval(showRemaining, 10);
But it does not handle month and year as that needs more complex calculations to factor 28-31 day months and leap years..
Demo at http://jsfiddle.net/TaHtz/2/
Try this js fiddle: http://jsfiddle.net/QH6X8/185/
Set the end date with the end variable defined on the first line of the JavaScript.
If you don't want to update every 1 millisecond, then here is a jsfiddle updating every 60: http://jsfiddle.net/QH6X8/187/
I would like a simple text box input of a date in the past and then for it to display how many days it is from today's date. I have found several examples of how to use javascript to do it between two dates that you input, but not with only doing one date and today's.
The current date to track is 4/2/2010, but it will change over time.
If you don't care about the leap second (:)), you can simply subtract the current date from the date back then, which gets you the difference in milliseconds, and then divide the difference by the amount of milliseconds that fits in one day:
var then = new Date(2010, 03, 02), // month is zero based
now = new Date; // no arguments -> current date
// 24 hours, 60 minutes, 60 seconds, 1000 milliseconds
Math.round((now - then) / (1000 * 60 * 60 * 24)); // round the amount of days
// result: 712
Here is a script I use for countdown timers. You can take out whatever parts you dont need to display just a day, time etc.
dateFuture = new Date(2029,2,4,23,59,59);
function GetCount(){
dateNow = new Date();
//grab current date
amount = dateFuture.getTime() - dateNow.getTime();
//calc milliseconds between dates
delete dateNow;
// time is already past
if(amount < 0){
document.getElementById('countbox').innerHTML="Now!";
}
// date is still good
else{
days=0;hours=0;mins=0;secs=0;out="";
amount = Math.floor(amount/1000);//kill the "milliseconds" so just secs
days=Math.floor(amount/86400);//days
amount=amount%86400;
hours=Math.floor(amount/3600);//hours
amount=amount%3600;
mins=Math.floor(amount/60);//minutes
amount=amount%60;
secs=Math.floor(amount);//seconds
if(days != 0){out += days +" day"+((days!=1)?"s":"")+",<br />";}
if(days != 0 || hours != 0){out += hours +" hour"+((hours!=1)?"s":"")+",<br />";}
if(days != 0 || hours != 0 || mins != 0){out += mins +" minute"+((mins!=1)?"s":"")+",<br />";}
out += secs +" seconds";
document.getElementById('countbox').innerHTML=out;
setTimeout("GetCount()", 1000);
}
}
window.onload=function(){GetCount();}//call when everything has loaded
<div id="countbox"><div>
I have a line of code that sets a cookie with an expiry date that looks like this.
var date = new Date();
date.setTime(date.getTime() + 1000*60*60*24*365);
var expires = "; expires=" + date.toGMTString();
What I'm trying to do is understand what each number represents. I know thats its just adding milliseconds to the time object but what does each one represent is the question.
1000 milliseconds in a second
60 seconds in a minute
60 minutes in an hour
24 hour in a day
365 days in a year
So, you'll get the quantity of milliseconds in a year.
var date = new Date(); // date object (now on this computer)
date.setTime( // change the time
date.getTime() // now in milliseconds since 1970
+ 1000 // milliseconds in a second
* 60 // seconds in a minut
* 60 // minutes in an hour
* 24 // hours in a day
* 365 // approximate days in a year. Total ~ number of milliseconds in a year
);
var expires = "; expires=" +
date.toGMTString(); // format the time to what the cookie likes
Please read
Date
toGMTString
for more information
1000 millicesonds times 60 seconds times 60 minutes times 24 hours times 365 days. It's a year.
Think about it like this:
1000*60*60*24*365
1000 // Converts milliseconds into seconds
60 // Converts seconds into minutes
60 // Convert minutes into hours
24 // Converts hours into days
365 // Convert days into year
1000 milliseconds per second,
60 seconds per minute,
60 minutes per hour,
24 hours in a day,
365 days in a year,
So it is adding the number of milliseconds in a year, advancing the time by a year