Javascript Count Days From Today - javascript

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>

Related

Convert milliseconds to hours or minute or hour or day in javascript

I am trying to convert milliseconds to ...(sec/min/hours/day) ago,
I have tried like the below code but I am not getting the expected result, the output is showing that 19143.4 Days. It should be 2 or 3 days.
function msToTime(ms) {
let seconds = (ms / 1000).toFixed(1);
let minutes = (ms / (1000 * 60)).toFixed(1);
let hours = (ms / (1000 * 60 * 60)).toFixed(1);
let days = (ms / (1000 * 60 * 60 * 24)).toFixed(1);
if (seconds < 60) return seconds + " Sec";
else if (minutes < 60) return minutes + " Min";
else if (hours < 24) return hours + " Hrs";
else return days + " Days"
}
console.log(msToTime(1653991056493))
In fact here your code seems to work fine.
Reading the Date documentation :
JavaScript Date objects represent a single moment in time in a platform-independent format. Date objects contain a Number that represents milliseconds since 1 January 1970 UTC.
So when you're doing new Date(1653991056493) it's 1653991056493ms after Jan 1st 1970 which is 19143.4 days.
If you want the ms between a date and the current date, you can just substract the current date with the timestamp
new Date() - 1653991056493
function msToTime(ms) {
let seconds = (ms / 1000).toFixed(1);
let minutes = (ms / (1000 * 60)).toFixed(1);
let hours = (ms / (1000 * 60 * 60)).toFixed(1);
let days = (ms / (1000 * 60 * 60 * 24)).toFixed(1);
if (seconds < 60) return seconds + " Sec";
else if (minutes < 60) return minutes + " Min";
else if (hours < 24) return hours + " Hrs";
else return days + " Days"
}
console.log(msToTime(new Date() - 1653991056493))
I interpretted the question slightly differently to the accepted answer and am posting this as it might help people seeking to do what I though was being asked:
namely to reduce an elapsed period of milliseconds to either (rounded) days OR (rounded) hours OR (rounded) minutes OR (rounded) seconds - dependent on which fits the scale of the elapsed duration (as one might want to do where, for example, a page is to report "comment made 2 days ago" or "comment made 10 seconds ago" etc. - just like SO does when reporting when answers or comments were made.
As with the accepted answer, the elapsed time has to first be calculated by subtracting the passed ms value from a new date value (and, since units smaller than seconds will never be needed, the elapsed value converted to seconds by dividing by 1000):
const now = new Date();
const secondsPast = Math.round((now-pastMs)/1000);
This value is then filtered down a series of if checks, each containing a conditional return statement if the relevant time unit has been reached. Thus, if the 'scale' is seconds (i.e the elapsed duration is less than a minute), the function returns the seconds value and exits immeadiately:
if (secondsPast<60) {return `${secondsPast} seconds`} // terminates here if true;
If the seconds value is greater than 60, minutes are checked and a return made if they are less than sixty. The process repeats until larger values are eventually returned as days if no other unit was appropriate. Note the use of Math.floor to only return whole numbers for the relevant unit.
(this is, I think, what the original question was trying to achieve).
function elapsedTime(pastMs) {
const now = new Date();
const secondsPast = Math.round((now-pastMs)/1000);
if (secondsPast<60) {return `${secondsPast} seconds`} // terminates here if true;
const minutesPast = Math.floor(secondsPast/60);
if (minutesPast<60) {return `${minutesPast} minutes`} // terminates here if true;
const hoursPast = Math.floor(minutesPast/60);
if (hoursPast<24) {return `${hoursPast} hours`} // terminates here if true;
return `${Math.floor(hoursPast/24)} days`;
} // end function elapsedTime;
console.log(elapsedTime(1653991056493))

Fallback countdown timer to be set to same day/time every week

If the user sets a date on the backend (via jQuery DateTimer Picker) the following acf_vars.timer variable would look like this on the frontend:
2021 2 9 13 08 00
I have the following construct as a countdown timer (CODEPEN):
const [y, month, d, h, minute, s] = acf_vars.timer.split(' ');
// monthIndex in Date Object begins with 0, so we subtract 1
const countDownDate = new Date(y, month - 1, d, h, minute, s).getTime();
const updateCountdown = () => {
const now = new Date().getTime(); // Get today's date and time
const distance = countDownDate - now; // Find distance between now and the countdown date
const expiredTimer = distance <= 0;
let days = Math.floor(distance / (1000 * 60 * 60 * 24));
let hours = Math.floor((distance % (1000 * 60 * 60 * 24)) / (1000 * 60 * 60));
let minutes = Math.floor((distance % (1000 * 60 * 60)) / (1000 * 60));
let seconds = Math.floor((distance % (1000 * 60)) / 1000);
if (expiredTimer) {
days = hours = minutes = seconds = 0;
clearInterval(timerInterval);
}
document.querySelectorAll('.ticker').forEach((container) => {
container.children[0].classList.contains('days') &&
(container.children[0].textContent = days);
container.children[2].classList.contains('hours') &&
(container.children[2].textContent = hours);
container.children[4].classList.contains('minutes') &&
(container.children[4].textContent = minutes);
container.children[6].classList.contains('seconds') &&
(container.children[6].textContent = seconds);
});
};
const timerInterval = setInterval(updateCountdown, 1000);
updateCountdown();
If the user doesn't specify a future date on the backend, I'd like to use a fallback which automatically sets the countdown timer to the upcoming Sunday at 9am. To solve this I tried setting a standardized countDownDate variable but I'm having trouble coming up with a way to set the day and time to automatically be the upcoming Sunday at 9am.
It seems you just want a way to set a date to next Sunday at 09:00. In plain JS it might be:
/* Get a date for next occurence of Sunday at 09:00
*
* #param {Date} d - start date, default is current date and time
* #returns {Date} for next Sunday at 09:00 after d
*/
function getNextSunday(d = new Date()) {
// Create date for next Sun at 9
let sun = new Date(d.getFullYear(), d.getMonth(), d.getDate() + (7 - (d.getDay() || 7)), 9, 0, 0, 0);
// If date is same day but later, move to next Sun
sun <= d? sun.setDate(sun.getDate() + 7) : null;
return sun;
}
// Examples
// Next Sunday at 9:00
console.log(getNextSunday().toString());
// Next Sunday after Sun 7 Feb at 8:59:59
console.log(getNextSunday(new Date(2021, 1, 7, 8, 59, 59)).toString());
// Next Sunday after Sun 7 Feb at 9:00
console.log(getNextSunday(new Date(2021, 1, 7, 9)).toString());
Notes:
d.getDay() || 7 is used so that if getDay returns 0 (Sunday), it's replaced with the number 7. That means the expression sets sun to the current day if it's Sunday or the next Sunday if it isn't. Otherwise on Sundays it would create a Date for the previous Sunday.
sun <= d? sun.setDate(sun.getDate() + 7) : null is used so that if the current date is Sunday but the time is after the specified time (in this case 9:00) the date is moved to the following Sunday at 9:00. Using the compound ? : operator this way is just a another way of writing if (sun <= d) sun.setDate(sun.getDate() + 7) on one line. I prefer if statements to be followed by a block and would rather use ? : for simple expressions on single lines.
Moment.js might be what you are looking for.
moment().endOf('week').add(1, 'second').add(9, 'hours').toString()
End of week uses the locale aware week start day, so you might have to configure it if you have users globally.
Edit
Alternatively, if you do not want to use external libraries you can check the current weekday and hour with the JavaScript Date object.
const day = countDownDate.getDay() // weekday sun = 0, sat = 6
const hour = countDownDate.getHours() // 0 - 23
Within your logic, you would want to get the distance between day and 0 (also accounting for countDownDate starting on a Sunday) and hour and 9. However, another way to implement this is to check the current date upon each update which could reduce the error in case the interval gets interrupted.

How to countdown and divide the time into segments?

I wish to do a countdown to a specific date and hour (January 10, 2018, 19:30). Which in large part I am able to do. Below code shows the remaining days, hours, minutes and seconds.
The tricky bit is to get certain periods of time. The countdown should respond to the following:
1. on the deadline day and hour show the message 'Now going live'. Which is 10 January 2018 19:30.
2. That same day but BEFORE 19:30 it should say 'Going live tonight'
3. The complete day before the deadline day (from 00:00 to 23:59) it should say 'last day'
4. The complete days before that it should say 'many days to go'
Step 1 and 2 I managed, but I'm having trouble getting the complete day before the deadline day and the complete days before that. That's because I'm not able to define the complete day before the deadline day (and the days before that). Because it counts '1 day' as 1 day before 10 January 19:30 (so it also takes those hours/minutes of 19:30 into account).
Step 1 and 2 I managed in the if-loop, but I can't figure out how to do step 3 and 4. Step 3 should say something like 'count one day, but before 10 January 2018 00:00. So it should subtract that 19:30 to get to 9 januari 2018 00:00-23:59. And the same for step 4. Can someone fix my code?
// Get todays date and time
var now = new Date().getTime();
// Set the date we're counting down to
var countDownDate = new Date("Januari 10, 2018 19:30").getTime();
// Find the distance between now an the count down date
var distance = countDownDate - now;
// Time calculations for days, hours, minutes and seconds
var days = Math.floor(distance / (1000 * 60 * 60 * 24));
var hours = Math.floor((distance % (1000 * 60 * 60 * 24)) / (1000 * 60 * 60));
var minutes = Math.floor((distance % (1000 * 60 * 60)) / (1000 * 60));
var seconds = Math.floor((distance % (1000 * 60)) / 1000);
// Display the result
this.timeleft.text = days + "d " + hours + "h " + minutes + "m " + seconds + "s ";
// countdown day 19:30
if ((days == 0) && (hours == 0) && (minutes == 0)) {
this.countdown.text = "NOW GOING LIVE!";
// countday day 00:00 - 19.30
} else if ((days == 0) && (hours <= 19) && (minutes <= 30)) {
this.countdown.text = "GOING LIVE TONIGHT!";
// 9 January 00:00 - 23:59
} else if ((days <= 1) && (hours >= 19) && (minutes >= 30)) {
this.countdown.text = "LAST DAY";
// days before 10 January
} else if (days >= 1) {
this.countdown.text = "MANY DAYS TO GO";
}
Since the "deadline" is hard-coded, you can hard-code everything and end up with something very simple:
var now = new Date().getTime();
var lastDayThreshold = new Date("January 9, 2018 00:00").getTime();
var liveTonightThreshold = new Date("January 10, 2018 00:00").getTime();
var countDownDate = new Date("January 10, 2018 19:30").getTime();
if (now < lastDayThreshold) this.countdown.text = "MANY DAYS TO GO";
else if(now < liveTonightThreshold) this.countdown.text = "LAST DAY";
else if(now < countDownDate) this.countdown.text = "LIVE TONIGHT";
else this.countdown.text = "NOW GOING LIVE";
Alex's answer was indeed what I was after. Those 'treshhold times' did the trick. Was thinking about improving it though as now I have to hard-code three dates/times. Preferably I would like to only specify the countDownDate date/time. And then let both Threshold dates calculate themselves. I tried to do that in a way, but ran into a problem. I know how to specify one day (1000 * 60 * 60 * 24), so I could subtract this 'oneday' value to get to the day before. But I wasn't able to calculate the milliseconds for the specified time 19:30. In order to read the miilliseconds since the beginning of January 10 until January 10 19:30. If I were able to do that it would look something like this (though I know this is incorrect, but you'll get the idea):
var oneday = 1000 * 60 * 60 * 24;
var countDownDate = new Date("January 10, 2018 19:30").getTime();
var lastDayThreshold = new Date(countDownDate - oneday "00:00").getTime();
var liveTonightThreshold = new Date(countDownDate "00:00").getTime();
You'll see my problem: for lastDayTreshold I could subtract one day of the countdowndate but then it would consider that 19:30 the previous day, not 00:00. And for liveTonightThreshold I also couldn't specify that I mean 00:00 of the countdowndate.
Would there be a way of doing that? Then I would just have to specify the countdown day and time and the rest would figure them out themselves.

Calculating the time difference in javascript

I want to create a time differance calculator between two given time and a date number.
Also I want to tell you that I have made 4 input fields: time1, time2, days and timediff.
The time format that I want is very simple, ex: 700 for 7:00, 932 for 9:32, 1650 for 16:50 and so on...
Now I also have the day input field, where I can put in some numbers, ex: 1(for the first day, 2 for the second day and so on).
I want that if I put 1(first day) to not calculate the days, only to calculate the timediff, because it's the same day. But if I put 2 on the date field then 24hours(one day) to be added to the timediff, if I put 3 48hours(two days) to be added and so on...
I have something like this, but is not working well, when I change the day the result is mess up...
var time1 = document.getElementById('indulas').value;
var time2 = document.getElementById('erkezes').value;
var day = document.getElementById('nap').value;
if (day > "1"){ day * 2400 };
var time = (time2 * day) - time1;
document.getElementById('ido').value = time;
This cannot be solved as subtraction of two times in format HHMM because hour has only 60 minutes (eg. 900 - 732 = 168 does not equal to the correct 1 hour and 28 minutes)
This script should work
function pad(num, size) { // num = number which gets the leading zeros; size = number of digits the string will have (in your case 2)
var s = num.toString(); // convert integer to string
while (s.length < size) s = "0" + s; // if number of digits is smaller than requested, add leading zeros
return s; // return the number (as string) with leading zeros
}
var time1 = document.getElementById('indulas').value.match(/.{2}/g),
// split string each 2 characters ("0932" -> ["09", "32"])
time2 = document.getElementById('erkezes').value.match(/.{2}/g),
// day 1 is today, day 2 - 1 adds 24 hours
days = parseInt(document.getElementById('nap').value)-1,
// start date on day 0 at HH, MM
startDate = new Date(0, 0, 0, parseInt(time1[0]), parseInt(time1[1])),
// end date on day 0 + days at HH, MM
endDate = new Date(0, 0, days, parseInt(time2[0]), parseInt(time2[1])),
// subtract dates in milliseconds
diff = endDate.getTime() - startDate.getTime(),
// hour and minute in miliseconds
hour_in_mili= 1000 * 60 * 60,
minute_in_mili = 1000 * 60,
// calculate number of hours in diff time
hours = Math.floor(diff / hour_in_mili),
// calculate number of minutes in the diff time what left after subtracting the hours
minutes = Math.floor((diff - (hours * hour_in_mili)) / minute_in_mili);
/*
if indulas.value = "0932", erkezes.value = "1650", nap.value = "1"
script shows "7:18"
*/
document.getElementById('ido').value = hours + ":" + pad(minutes, 2);

JavaScript difference between two Date()'s in months [duplicate]

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')

Categories

Resources