I try to get the function for my JavaScript countdown running every second but somehow I don't get the setInterval function to work.
This is how the JS code looks so far:
// Set end date and time
var enddate = new Date();
endTimeDate = "2022-01-12 21:52";
// Get date and time of today
var today = new Date();
// Calculate date and time difference
function getTimeDifference(endtime) {
var total = Date.parse(endtime) - Date.parse(today);
var seconds = Math.floor((total/1000) % 60);
var minutes = Math.floor((total/1000/60) % 60);
var hours = Math.floor((total/1000/60/60) % 24);
var days = Math.floor(total/1000/60/60/24);
return {
total,
days,
hours,
minutes,
seconds
};
}
function runCountdown() {
var t = getTimeDifference(endTimeDate);
document.getElementById('days').innerHTML = t.days + " D";
document.getElementById('hours').innerHTML = t.hours + " H";
document.getElementById('minutes').innerHTML = t.minutes + " M";
document.getElementById('seconds').innerHTML = t.seconds + " S";
}
window.setInterval(runCountdown, 1000);
The reason your code is not working as expected because you're declaring today outside of the function which means it's called only once , hence the diff result will always be the same. You probably want to move the assignment and the declaration of var today = new Date(); inside the getTimeDifference function so there will be an actual difference between the enddate value and the today value.
// Set end date and time
var enddate = new Date();
endTimeDate = "2022-01-12 21:52";
// Get date and time of today
// Calculate date and time difference
function getTimeDifference(endtime) {
var today = new Date();
console.log(endtime);
var total = Date.parse(endtime) - Date.parse(today);
var seconds = Math.floor((total/1000) % 60);
var minutes = Math.floor((total/1000/60) % 60);
var hours = Math.floor((total/1000/60/60) % 24);
var days = Math.floor(total/1000/60/60/24);
return {
total,
days,
hours,
minutes,
seconds
};
}
function runCountdown() {
var t = getTimeDifference(endTimeDate);
document.getElementById('days').innerHTML = t.days + " D";
document.getElementById('hours').innerHTML = t.hours + " H";
document.getElementById('minutes').innerHTML = t.minutes + " M";
document.getElementById('seconds').innerHTML = t.seconds + " S";
}
window.setInterval(runCountdown, 1000);
<div id="days">
</div>
<div id="hours">
</div>
<div id="minutes">
</div>
<div id="seconds">
</div>
Related
This question already has answers here:
how to convert the minutes into hours and minutes with subtracted time(subtracted time values)
(4 answers)
Closed 4 years ago.
What I have:
Three time inputs consisting of a start time, end time and the difference between the two.
<input type="time" name="starttime" id="starttime">
<input type="time" name="endtime" id="endtime">
<input type="time" name="duration" id="duration" disabled>
What I need:
When the start or end time changes, the difference shows in the third input.
e.g. 23:15 - 20:00 = 03:15.
What I've tried:
So far, I can only produce the correct hours but not the minutes.
<script>
jQuery(document).ready(function($) {
function calculateTime() {
// Get values.
var valuestart = $("#starttime").val();
var valuestop = $("#endtime").val();
// Create date format.
var timeStart = new Date("01/01/2007 " + valuestart);
var timeEnd = new Date("01/01/2007 " + valuestop);
// Subtract.
var difference = timeEnd - timeStart;
// Attempt 1: Only gets hours.
//var difference_as_hours = difference / 60 / 60 / 1000;
//alert("Hour Difference: " + difference_as_hours);
// Attempt 2: Nothing happens.
//var difference_as_hours_and_minutes = difference.getHours() + ":" + difference.getMinutes();
//alert("Hour And Minutes Difference: " + difference_as_hours_and_minutes);
// Attempt 3: Nothing happens.
//var difference_as_date = new Date("01/01/2007 " + difference);
//var difference_as_hours_and_minutes = difference_as_date.getHours() + ":" + difference_as_date.getMinutes();
//alert("Hour And Minutes Difference: " + difference_as_hours_minutes);
// Attempt 4: Nothing happens.
var formatted_time = time_format(difference);
alert(formatted_time);
}
$("#starttime, #endtime").change(calculateTime);
calculateTime();
});
function time_format(d) {
hours = format_two_digits(d.getHours());
minutes = format_two_digits(d.getMinutes());
seconds = format_two_digits(d.getSeconds());
return hours + ":" + minutes + ":" + seconds;
}
function format_two_digits(n) {
return n < 10 ? "0" + n : n;
}
</script>
How can I produce the hours and minutes?
Check below working Demo using momentjs:
let valuestart = moment.duration("20:00", "HH:mm");
let valuestop = moment.duration("23:15", "HH:mm");
let difference = valuestop.subtract(valuestart);
console.log(difference.hours() + ":" + difference.minutes())
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.22.2/moment.js"></script>
You try
function calculateTime() {
// Get values.
var valuestart = $("#starttime").val();
var valuestop = $("#endtime").val();
// Create date format.
var timeStart = new Date("01/01/2007 " + valuestart);
var timeEnd = new Date("01/01/2007 " + valuestop);
// Subtract.
var difference = timeEnd - timeStart;
var time = msToTime(difference);
console.log(time);
}
function msToTime(s) {
var ms = s % 1000;
s = (s - ms) / 1000;
var secs = s % 60;
s = (s - secs) / 60;
var mins = s % 60;
var hrs = (s - mins) / 60;
return hrs + ':' + mins + ':' + secs + '.' + ms;
}
$("#starttime, #endtime").change(calculateTime);
I'm getting date from the API in this format 14:30:00 inside "this.StartTime". My question is how can I calculate the time difference between the date I'm getting inside "this.StartTime" and present date?
Following is my component.ts code:-
getBookingDetails() {
this._CounsellingService.getBookingDetails().subscribe(
response => {
this.sessionDetails = response;
this.StartTime = this.sessionDetails.StartTime;
}
);
}
You can create a date today and then set its time part as startDate. Then compare it with current time;
var startTime = "14:30:00".split(":");
var h = startTime[0];
var m = startTime[1];
var s = startTime[2];
var now = new Date();
startTime = new Date(now);
startTime.setHours(h);
startTime.setMinutes(m);
startTime.setSeconds(s);
difference = startTime.getTime() - now.getTime();
console.log(msToTime(difference))
function msToTime(s) {
var ms = s % 1000;
s = (s - ms) / 1000;
var secs = s % 60;
s = (s - secs) / 60;
var mins = s % 60;
var hrs = (s - mins) / 60;
return hrs + ':' + mins + ':' + secs + '.' + ms;
}
So I have two strings in javascript:
old_date = "2010-11-10 07:30:40";
new_date = "2010-11-15 08:03:22";
I want to find the difference between these two dates, but I am totally at a loss :(
I tried to do the following:
old_date_obj = new Date(Date.parse(old_date));
new_date_obj = new Date(Date.parse(new_date));
But it is giving me error. However that is only start of my woes...I need to show the difference as:
Difference is X Days, Y hours and Z minutes
Can JavaScript/jQuery gurus help me please? Much appreciated...
<script>
function Calculate() {
old_date = "2010-11-10 07:30:40";
new_date = "2010-11-15 08:03:22";
old_date_obj = new Date(Date.parse(old_date, "dd/mm/yyyy HH:mm:ss"));
new_date_obj = new Date(Date.parse(new_date, "dd/mm/yyyy HH:mm:ss"));
var utc1 = Date.UTC(new_date_obj.getFullYear(), new_date_obj.getMonth(), new_date_obj.getDate());
var utc2 = Date.UTC(old_date_obj.getFullYear(), old_date_obj.getMonth(), old_date_obj.getDate());
alert(Math.floor((utc2 - utc1) / (1000 * 60 * 60 * 24)));
}
</script>
simply add in you date and it will work for you.
"2010-11-10T07:30:40+01:00"
for more detail check this answer
Answer in detail
<script type="text/javascript">
// The number of milliseconds in one day, hour, and minute
var ONE_DAY = 1000 * 60 * 60 * 24;
var ONE_HOUR = 1000 * 60 * 60;
var ONE_MINUTE = 1000 * 60;
var old_date = "2010-11-10T07:30:40";
var new_date = "2010-11-15T08:03:22";
// Convert both dates to milliseconds
var old_date_obj = new Date(old_date).getTime();
var new_date_obj = new Date(new_date).getTime();
// Calculate the difference in milliseconds
var difference_ms = Math.abs(new_date_obj - old_date_obj)
// Convert back to days, hours, and minutes
var days = Math.round(difference_ms / ONE_DAY);
var hours = Math.round(difference_ms / ONE_HOUR) - (days * 24) - 1;
var minutes = Math.round(difference_ms / ONE_MINUTE) - (days * 24 * 60) - (hours * 60);
alert('Difference is ' + days + ' days, ' + hours + ' hours and ' + minutes + ' minutes.' );
</script>
<script type="text/javascript">
function getDates(strDate1, strDate2) {
/*Now strDate1 and strDate2 string. So we should convert them to javascript datetime value.*/
var tempDate1 = strDate1.split(/\-|\s/)
var date1 = new Date(tempDate1.slice(0,3).reverse().join('/')+' '+tempDate1[3]);
var tempDate2 = strDate2.split(/\-|\s/)
var date2 = new Date(tempDate2.slice(0,3).reverse().join('/')+' '+tempDate2[3]);
var obj1 = $.datepicker.parseDate('dd.mm.yy', $("#date1").val());
var obj2 = $.datepicker.parseDate('dd.mm.yy', $("#date2").val());
console.log(findDifferentDate(obj1, obj2));
}
function findDifferentDate(obj1, obj2){
var date1 = getFormattedDate(obj1);
var date2 = getFormattedDate(obj2);
var year = date1.getFullYear() - date2.getFullYear();
var day = date1.getDate() - date2.getDate();
var month = date1.getMonth() - date2.getMonth();
var seconds = date1.getSeconds() - date2.getSeconds();
var minutes = date1.getMinutes() - date2.getMinutes();
var hour = date1.getHours() - date2.getHours();
return 'Difference is' + day + 'Days' + month + 'Months' + year + 'Years' + seconds + 'Seconds' + minutes + 'Minutes' + hour + 'Hours';
}
function getFormattedDate(date) {
var year = date.getFullYear();
var month = (1 + date.getMonth()).toString();
month = month.length > 1 ? month : '0' + month;
var day = date.getDate().toString();
day = day.length > 1 ? day : '0' + day;
return day + '.' + month + '.' + year;
}
</script>
If you call getDates method with your dates and then u can see difference time in the console.
var old_date = "2010-11-15 07:30:40";
var new_date = "2010-11-15 08:03:22";
var old_date_obj = new Date(Date.parse(old_date));
var new_date_obj = new Date(Date.parse(new_date));
var diffMs = Math.abs(new_date_obj - old_date_obj);
var diffDays = Math.round(diffMs / 86400000); // days
var diffHrs = Math.round((diffMs % 86400000) / 3600000); // hours
var diffMins = Math.round(((diffMs % 86400000) % 3600000) / 60000); // minutes
https://jsfiddle.net/yps2wb58/1/
I am using following code to display date on my webpage. I need to update it every minute. How to do that?
var d=new Date();
var n=d.toString();
document.write(n);
Currently its static, means when the page load, datetime of that moment is displayed. I have to update time every minutes without refreshing the page.
Try with setInterval(): http://jsfiddle.net/4vQ8C/
var nIntervId; //<----make a global var in you want to stop the timer
//-----with clearInterval(nIntervId);
function updateTime() {
nIntervId = setInterval(flashTime, 1000*60); //<---prints the time
} //----after every minute
function flashTime() {
var now = new Date();
var h = now.getHours();
var m = now.getMinutes();
var s = now.getSeconds();
var time = h + ' : ' + m + ' : ' + s;
$('#my_box1').html(time); //<----updates the time in the $('#my_box1') [needs jQuery]
}
$(function() {
updateTime();
});
You can use document.getElementById("my_box1").innerHTML=time; instead of $('#my_box1')
from MDN:
About setInterval : --->Calls a function or executes a code snippet repeatedly, with a fixed time delay between each call to that function.
About setTimeout : ----> Calls a function or executes a code snippet after specified delay.
Here is how you can print date time every second
function displayDate()
{
var n=BuildDateString();
document.write(n);
window.setTimeout("displayDate();", 1000); // to print it every minute take 1000*60
}
function BuildDateString()
{
var today = new Date()
var year = today.getYear()
if (year < 2000)
year = "19" + year
var _day = today.getDate()
if (_day < 10)
_day = "0" + _day
var _month = today.getMonth() + 1
if (_month < 10)
_month = "0" + _month
var hours = today.getHours()
var minutes = today.getMinutes()
var seconds = today.getSeconds()
var dn = "AM"
if (hours > 12)
{
dn = "PM"
hours = hours - 12
}
if (hours == 0)
hours = 12
if (minutes < 10)
minutes = "0" + minutes
if (seconds < 10)
seconds = "0" + seconds
var DateString = _month+"/"+_day+"/"+year+" "+hours+":"+minutes+":"+seconds+" "+dn
return DateString;
}
I am using following approach:
var myVar=setInterval(function(){myDateTimer()},60000);
function makeArray()
{
for (i = 0; i<makeArray.arguments.length; i++)
this[i + 1] = makeArray.arguments[i];
}
function myDateTimer()
{
var months = new makeArray('January','February','March','April','May',
'June','July','August','September','October','November','December');
var days = ['Sunday','Monday','Tuesday','Wednesday','Thursday','Friday','Saturday'];
var date = new Date();
var day = date.getDate();
var month = date.getMonth() + 1;
var yy = date.getYear();
var year = (yy < 1000) ? yy + 1900 : yy;
var hours = date.getHours();
var minutes = date.getMinutes();
var finaldate = days[ date.getDay() ] + ", " + months[month] + " " + day + ", " + year + " " + hours +" : " + minutes;
document.getElementById("showDateTime").innerHTML=finaldate;
}
just do this
$(function(){
setInterval(function(){
var d=new Date();
var n=d.toString();
$('#test').html(n);
},1000);
});
demo http://runjs.cn/code/txlexzuc
This question already has answers here:
How to measure time taken by a function to execute
(30 answers)
Closed 9 years ago.
I am looking for some JavaScript simple samples to compute elapsed time. My scenario is, for a specific point of execution in JavaScript code, I want to record a start time. And at another specific point of execution in JavaScript code, I want to record an end time.
Then, I want to calculate the elapsed time in the form of: how many Days, Hours, Minutes and Seconds are elapsed between end time and start time, for example: 0 Days, 2 Hours, 3 Minutes and 10 Seconds are elapsed.
Any reference simple samples? :-)
Thanks in advance,
George
Try something like this (FIDDLE)
// record start time
var startTime = new Date();
...
// later record end time
var endTime = new Date();
// time difference in ms
var timeDiff = endTime - startTime;
// strip the ms
timeDiff /= 1000;
// get seconds (Original had 'round' which incorrectly counts 0:28, 0:29, 1:30 ... 1:59, 1:0)
var seconds = Math.round(timeDiff % 60);
// remove seconds from the date
timeDiff = Math.floor(timeDiff / 60);
// get minutes
var minutes = Math.round(timeDiff % 60);
// remove minutes from the date
timeDiff = Math.floor(timeDiff / 60);
// get hours
var hours = Math.round(timeDiff % 24);
// remove hours from the date
timeDiff = Math.floor(timeDiff / 24);
// the rest of timeDiff is number of days
var days = timeDiff ;
Try this...
function Test()
{
var s1 = new StopWatch();
s1.Start();
// Do something.
s1.Stop();
alert( s1.ElapsedMilliseconds );
}
// Create a stopwatch "class."
StopWatch = function()
{
this.StartMilliseconds = 0;
this.ElapsedMilliseconds = 0;
}
StopWatch.prototype.Start = function()
{
this.StartMilliseconds = new Date().getTime();
}
StopWatch.prototype.Stop = function()
{
this.ElapsedMilliseconds = new Date().getTime() - this.StartMilliseconds;
}
Hope this will help:
<!doctype html public "-//w3c//dtd html 3.2//en">
<html>
<head>
<title>compute elapsed time in JavaScript</title>
<script type="text/javascript">
function display_c (start) {
window.start = parseFloat(start);
var end = 0 // change this to stop the counter at a higher value
var refresh = 1000; // Refresh rate in milli seconds
if( window.start >= end ) {
mytime = setTimeout( 'display_ct()',refresh )
} else {
alert("Time Over ");
}
}
function display_ct () {
// Calculate the number of days left
var days = Math.floor(window.start / 86400);
// After deducting the days calculate the number of hours left
var hours = Math.floor((window.start - (days * 86400 ))/3600)
// After days and hours , how many minutes are left
var minutes = Math.floor((window.start - (days * 86400 ) - (hours *3600 ))/60)
// Finally how many seconds left after removing days, hours and minutes.
var secs = Math.floor((window.start - (days * 86400 ) - (hours *3600 ) - (minutes*60)))
var x = window.start + "(" + days + " Days " + hours + " Hours " + minutes + " Minutes and " + secs + " Secondes " + ")";
document.getElementById('ct').innerHTML = x;
window.start = window.start - 1;
tt = display_c(window.start);
}
function stop() {
clearTimeout(mytime);
}
</script>
</head>
<body>
<input type="button" value="Start Timer" onclick="display_c(86501);"/> | <input type="button" value="End Timer" onclick="stop();"/>
<span id='ct' style="background-color: #FFFF00"></span>
</body>
</html>
Something like a "Stopwatch" object comes to my mind:
Usage:
var st = new Stopwatch();
st.start(); //Start the stopwatch
// As a test, I use the setTimeout function to delay st.stop();
setTimeout(function (){
st.stop(); // Stop it 5 seconds later...
alert(st.getSeconds());
}, 5000);
Implementation:
function Stopwatch(){
var startTime, endTime, instance = this;
this.start = function (){
startTime = new Date();
};
this.stop = function (){
endTime = new Date();
}
this.clear = function (){
startTime = null;
endTime = null;
}
this.getSeconds = function(){
if (!endTime){
return 0;
}
return Math.round((endTime.getTime() - startTime.getTime()) / 1000);
}
this.getMinutes = function(){
return instance.getSeconds() / 60;
}
this.getHours = function(){
return instance.getSeconds() / 60 / 60;
}
this.getDays = function(){
return instance.getHours() / 24;
}
}
var StopWatch = function (performance) {
this.startTime = 0;
this.stopTime = 0;
this.running = false;
this.performance = performance === false ? false : !!window.performance;
};
StopWatch.prototype.currentTime = function () {
return this.performance ? window.performance.now() : new Date().getTime();
};
StopWatch.prototype.start = function () {
this.startTime = this.currentTime();
this.running = true;
};
StopWatch.prototype.stop = function () {
this.stopTime = this.currentTime();
this.running = false;
};
StopWatch.prototype.getElapsedMilliseconds = function () {
if (this.running) {
this.stopTime = this.currentTime();
}
return this.stopTime - this.startTime;
};
StopWatch.prototype.getElapsedSeconds = function () {
return this.getElapsedMilliseconds() / 1000;
};
StopWatch.prototype.printElapsed = function (name) {
var currentName = name || 'Elapsed:';
console.log(currentName, '[' + this.getElapsedMilliseconds() + 'ms]', '[' + this.getElapsedSeconds() + 's]');
};
Benchmark
var stopwatch = new StopWatch();
stopwatch.start();
for (var index = 0; index < 100; index++) {
stopwatch.printElapsed('Instance[' + index + ']');
}
stopwatch.stop();
stopwatch.printElapsed();
Output
Instance[0] [0ms] [0s]
Instance[1] [2.999999967869371ms] [0.002999999967869371s]
Instance[2] [2.999999967869371ms] [0.002999999967869371s]
/* ... */
Instance[99] [10.999999998603016ms] [0.010999999998603016s]
Elapsed: [10.999999998603016ms] [0.010999999998603016s]
performance.now() is optional - just pass false into StopWatch constructor function.
This is what I am using:
Milliseconds to a pretty format time string:
function ms2Time(ms) {
var secs = ms / 1000;
ms = Math.floor(ms % 1000);
var minutes = secs / 60;
secs = Math.floor(secs % 60);
var hours = minutes / 60;
minutes = Math.floor(minutes % 60);
hours = Math.floor(hours % 24);
return hours + ":" + minutes + ":" + secs + "." + ms;
}
First, you can always grab the current time by
var currentTime = new Date();
Then you could check out this "pretty date" example at http://www.zachleat.com/Lib/jquery/humane.js
If that doesn't work for you, just google "javascript pretty date" and you'll find dozens of example scripts.
Good luck.
<script type="text/javascript">
<!-- Gracefully hide from old browsers
// Javascript to compute elapsed time between "Start" and "Finish" button clicks
function timestamp_class(this_current_time, this_start_time, this_end_time, this_time_difference) {
this.this_current_time = this_current_time;
this.this_start_time = this_start_time;
this.this_end_time = this_end_time;
this.this_time_difference = this_time_difference;
this.GetCurrentTime = GetCurrentTime;
this.StartTiming = StartTiming;
this.EndTiming = EndTiming;
}
//Get current time from date timestamp
function GetCurrentTime() {
var my_current_timestamp;
my_current_timestamp = new Date(); //stamp current date & time
return my_current_timestamp.getTime();
}
//Stamp current time as start time and reset display textbox
function StartTiming() {
this.this_start_time = GetCurrentTime(); //stamp current time
document.TimeDisplayForm.TimeDisplayBox.value = 0; //init textbox display to zero
}
//Stamp current time as stop time, compute elapsed time difference and display in textbox
function EndTiming() {
this.this_end_time = GetCurrentTime(); //stamp current time
this.this_time_difference = (this.this_end_time - this.this_start_time) / 1000; //compute elapsed time
document.TimeDisplayForm.TimeDisplayBox.value = this.this_time_difference; //set elapsed time in display box
}
var time_object = new timestamp_class(0, 0, 0, 0); //create new time object and initialize it
//-->
</script>
<form>
<input type="button" value="Start" onClick="time_object.StartTiming()"; name="StartButton">
</form>
<form>
<input type="button" value="Finish" onClick="time_object.EndTiming()"; name="EndButton">
</form>
<form name="TimeDisplayForm">
Elapsed time:
<input type="text" name="TimeDisplayBox" size="6">
seconds
</form>
write java program that enter elapsed time in seconds for any cycling event & the output format should be like (hour : minute : seconds ) for EX : elapsed time in 4150 seconds= 1:09:10