Javascript's date object toLocaleTimeString adds an hour - javascript

I'm trying to create a timer from when the user clicks a button.
To do this I tried to calculate the difference between two date objects. When I output the difference, it works. However thetoLocaleTimeString call returns a string with an extra hour added:
var start;
var timer;
function myTimer() {
var current = new Date();
var difference = new Date(current - start);
console.log(difference.getTime(), difference.toLocaleTimeString(navigator.language));
document.getElementById("timer").innerHTML = difference;
document.getElementById("timer2").innerHTML = difference.toLocaleTimeString('en-GB');
}
start = new Date();
timer = setInterval(myTimer, 1000);
draw();
<h1 id="timer"></h1>
<h1 id="timer2"></h1>
What am I doing wrong?

Specify the time zone as UTC in the options argument. Otherwise, the difference date will be adjusted to the user agent's time zone.
document.getElementById("timer2").innerHTML = difference.toLocaleTimeString('en-GB', { timeZone: 'UTC' });
Read more on the options argument and toLocaleTimeString in the MDN documentation.
var start;
var timer;
function myTimer() {
var current = new Date();
var difference = new Date(current - start);
console.log(difference.getTime(), difference.toLocaleTimeString(navigator.language));
document.getElementById("timer").innerHTML = difference;
document.getElementById("timer2").innerHTML = difference.toLocaleTimeString(navigator.language, { timeZone: 'UTC', hour12: false });
}
start = new Date();
timer = setInterval(myTimer, 1000);
draw();
<h1 id="timer"></h1>
<h1 id="timer2"></h1>

Because of the problems with JS and timezones, you are better of using something like moment.js's timezone (http://momentjs.com/timezone/) to do correct conversions (that keep in mind the shift of BST, GMT, differences between countries, etc..). For the purpose of your timer, the following would work as well, and is more accurate as well as simpler to reason about:
// Use Date.now() to get the time in milliseconds for this local computer
var start = Date.now();
var time = new Date();
// This function will prepend a 0 to a number lower than 10
function prependZero(v){
if(v < 9) return '0' + v;
else return v;
}
var timer = setInterval(function() {
// Calculate the difference using the computers local time strings
var difference = new Date(Date.now() - start);
document.getElementById("timer").innerHTML = new Date();
// Now use the Date mnethods to get the correct output:
document.getElementById("timer2").innerHTML = prependZero(difference.getHours()) + ':' + prependZero(difference.getMinutes()) + ':' + prependZero(difference.getSeconds());
}, 1000);
<h1 id="timer"></h1>
<h1 id="timer2"></h1>

Related

create date object by hours and minutes

I want to setup a setTimeout function and need to calculate the seconds for the callback. Let's say I want to execute a function at 12:00 (HH-MM) I have to calculate the timespan up to this time. If the time has already passed the next day is relevant.
I get the current date time with new Date()
I know I can calculate the timespan in seconds by using
const difference = dateTimeOne.getTime() - dateTimeTwo.getTime();
const differenceInSeconds = difference / 1000;
Is there a way creating a second date object by passing in the hours and minutes or do I have to calculate it on my own?
An example would be new Date('12:45')
var minutes = 42;
for (var hours = 1; hours < 24; hours+=3) {
var newAlarm = setAlarm(hours, minutes);
out(newAlarm)
}
function out(date) {
var now = new Date()
if (date.getDate() != now.getDate()) {
console.log('tomorrow: ' + date.getHours() + ":" + date.getMinutes())
} else {
console.log('today: ' + date.getHours() + ":" + date.getMinutes())
}
}
function setAlarm(hours, minutes) {
var now = new Date();
var dateTarget = new Date();
dateTarget.setHours(hours)
dateTarget.setMinutes(minutes)
dateTarget.setSeconds(0)
dateTarget.setMilliseconds(0)
if (dateTarget < now) {
dateTarget.setDate(dateTarget.getDate()+1)
}
return dateTarget
}
See this Documentation on MDN
You can manipulate the date and then check whether it is in the past. If it is, just add another day.
const d = new Date();
d.setHours(12);
d.setMinutes(0);
d.setSeconds(0);
d.setMilliseconds(0);
if (d < new Date()) {
d.setDate(d.getDate() + 1);
}
console.log(d);
It's possible, but you need to provide the whole time string (which we can get from calling Date() and add the missing part):
const time = '12:45'
const current = new Date()
const dateTimeTwo = new Date(`${current.getFullYear()}-${current.getMonth()+1}-${current.getDate()} ${time}`)

js different variable same value

Currently i'm facing the following problem. In my JavaScript code, i have a function, which should calculate the weeks from now, to a given timestamp. The problem is, that the the first value has the same Value as another variable with another name. The code:
let myAppointment = event.data.toTime;
console.log(myAppointment);
let currentDate = new Date(Date.now());
let currentTime = (convertStringDateToDate(currentDate.getFullYear(), currentDate.getMonth(), currentDate.getDate(), 0,0,0,0)).getTime();
let appointmentStartDate = new Date(myAppointment.getStart());
console.log(appointmentStartDate);
console.log(currentDate);
let appointmentStartTime = (convertStringDateToDate(appointmentStartDate.getFullYear(), appointmentStartDate.getMonth(), appointmentStartDate.getDate(),0,0,0,0)).getTime();
console.log('AppointmentStartTime : ' + appointmentStartTime);
console.log('CurrentTime: ' + currentTime);
let timeskip = appointmentStartTime - currentTime;
console.log(timeskip + ' timeskip / 604800000 = ' + (timeskip / 604800000));
skips = timeskip / 604800000;
await displayCalendar(document.getElementById('wrapper'));
console.log(skips);
if(skips < 0){
skips = Math.floor(skips);
if(Math.abs(skips) != 1){
navigateBackward(skips);
}
}else{
skips = Math.floor(skips);
if(Math.abs(skips) != 1){
navigateForward(skips);
}
}
cleanTable();
displayAppointments();
});
//i think this function may be interesting too, but the error can't occur from here
function
convertStringDateToDate(year,month,day,hours,minutes,seconds,milliseconds){
let date = new Date();
date.setFullYear(year);
date.setMonth(month);
date.setDate(day);
date.setHours(hours);
date.setMinutes(minutes);
date.setSeconds(seconds);
date.setMilliseconds(milliseconds);
return date;
}
The function from let myAppointment = ... Leads to the following console output
The problem lies here:
let appointmentStartTime = (convertStringDateToDate(appointmentStartDate.getFullYear(), appointmentStartDate.getMonth(), appointmentStartDate.getDate(),0,0,0,0)).getTime();
You set the hours, minutes, seconds all to zero - effectively turning your start date to the same value as today's date.
Note that in your particular example, currentDate and appointmentStartDate share the same year, month, and date. When you call let currentTime = (convertStringDateToDate(currentDate.getFullYear(), currentDate.getMonth(), currentDate.getDate(), 0,0,0,0)).getTime();
, you should replace 0,0,0,0 with correct values for both currentTime and appointStartTime.
To make your coding style consistent, you can use date.getHours(), date.getMinutes(), date.getSeconds(), and date.getMilliseconds() to replace those four zeroes.
Also, if you want to shorten your code, you can get rid of convertStringDateToDate() and merely call getTime() on currentDate and appointStartDate.
let currentDate = new Date();
let currentTime = (convertStringDateToDate(currentDate.getFullYear(), currentDate.getMonth(), currentDate.getDate(), currentDate.getHours(),currentDate.getMinutes(),currentDate.getSeconds(),currentDate.getMilliseconds())).getTime();
console.log(currentTime); // 1537309553647
console.log(currentDate.getTime()); // 1537309553647

Continue a clicking clock when user chooses new time in JavaScript

I've run into a problem whilst building a clock using Vanilla Javascript.
I'm getting the current time fine but I would like the user to be able to set their own time. The time the user wants is grabbed from three input fields and passed in as optional paramters(updateH,updateM,updateS) to the below function:
function updateTime(updateH,updateM,updateS){
updateH = updateH || false; updateM = updateM || false; updateS = updateS || false;
today = new Date();
if (updateH != false || updateM != false || updateS != false) {
today.setHours(updateH);
today.setMinutes(updateM);
today.setSeconds(updateS);
}
h = addLeadingZeroes(today.getHours()); //Today's time (hours)
m = addLeadingZeroes(today.getMinutes()); //Today's time (minutes)
s = addLeadingZeroes(today.getSeconds()); //Today's time (seconds)
day = getDay().toUpperCase(); //Today's date (day)
date = today.getaDmante(); //Today's date (date)
month = getMonth().toUpperCase(); //Today's date (month)
time24H = h + ":" + m + ":" + s;
drawWatch();
setTimeout(updateTime, 1000);
}
updateTime();
This function is ran every second (1000ms), therefore the clock resets itself to the current time after one second, making the users choice time dissapear.
Is there anyway to update the time to the user passed in time and then continue the clock ticking using the new time? E.G:
The clock reads '12:00:00', the user then enters the time '13:30:00', now the clock continues ticking from '13:30:01....13:30:02....13:30:03...ETC'.
Many thanks for your help!
When the user sets the their time, calculate the difference between their time and the current time, store this value. Then each time you want to redraw the watch just get the new current time, subtract that stored difference and redraw the watch.
Personally I would create a new prototype called "Watch" and just do all the things you want within this object.
/* Create a "Watch" prototype */
function Watch(hours, minutes, seconds, drawInterval){
var t = this;
this.offset = 0;
this.drawInterval = drawInterval || 1000;
this.setTime = function(hours, minutes, seconds){
var now = new Date().getTime();
var theirTime = new Date();
if(hours) theirTime.setHours(hours);
if(minutes) theirTime.setMinutes(minutes);
if(seconds) theirTime.setSeconds(seconds);
this.offset = now - theirTime.getTime();
};
this.getTime = function(){
var d = new Date( new Date() - this.offset );
return d.getHours()+":"+d.getMinutes()+":"+d.getSeconds();
};
this.draw = function(elementID){
function draw(){
document.getElementById(elementID).innerHTML = t.getTime();
setTimeout(draw, t.drawInterval);
};
draw();
};
this.setTime(hours, minutes, seconds); // Initialize
}
/* Create an instance of the "Watch" prototype */
var W = new Watch();
/* Draw the watch to the DOM */
W.draw("watch");
/* Set the Users Time */
W.setTime(12,45,30); // 12:45:30
<div id='watch'></div>

PHP Time to Javascript Clock

I want to simply just pull the time from the server.
And continue it ticking with javascript.
My PHP.
//Get current UNIX timestamp (no offset, just straight timestamp)
$time = time()*1000;
//Get offset of server time
$offset = date('O');
// Convert into a new timestamp based on the timezone
$newtime = $time+$offset;
// a vardump($newtime) here gives me
// 1415169764400
My Javascript...
$(document).ready(function(){
// Here Im putting the server time into a variable
var serverTime = "<?php echo $newtime;?>";
//console.log(serverTime) gives me 1415169764400
// Local computer time into a variable
var localTime = new Date().getTime();
//console.log(localTime) here gives me 1415170692954
// Offset between the computer and the server
var timeDiff = serverTime - localTime;
// console.log(timeDiff) here gives me -928554
//The ticking clock function
setInterval(function () {
// Set clock to Computer time plus the time difference
var today = new Date(Date.now()+timeDiff);
var h=today.getHours();
var m=today.getMinutes();
var s=today.getSeconds();
m = checkTime(m); //checktime() is just a leading zero function
s = checkTime(s); // checktime() is just a leading zero function
var formatted = h+":"+m+":"+s;
$('.serverTime').html(formatted);
}, 2000);
//PROBLEM IS THAT THIS DISPLAYS THE CURRENT TIME ON MY COMPUTER
// NO MATTER WHAT I TRY, IT ALWAYS JUST DISPLAYS THE LOCAL TIME
// No matter what PHP timezone I put.
// The time Diff and server times are working properly.
// Any ideas whats happening!!???
});
I normally would just use the users local computer time, but each server is in a different location, and when they are visiting this page, I want the clock to tick to the server they're currently visiting.
$time is the number of seconds since unix epoch, expressed as milliseconds. $offset is the number of hours difference from GMT*, Eg '-0800'. Your first problem is that you are adding the offset to the timestamp. At most, you are changing the time by 1.4 seconds, where you seem to intend to change the time by hours.
It would be much easier if you use a DateTime object instead. Then you can call .getOffset() which gives you the difference in seconds:
<?php
$date = new DateTime();
// Get offset for UNIX timestamp based on server timezone
$time = $date->getTimestamp();
//Get offset of server time
$offset = $date->getOffset();
// Convert into a new timestamp based on the timezone
$newtime = ($time + $offset) * 1000;
?>
So far, we've been dealing only with UTC dates. Your other problem is that you are using the local date methods to get values out. You should use the UTC versions of these methods.
//Actual ticking clock
setInterval(function () {
var today = new Date(Date.now() + timeDiff);
var h=today.getUTCHours();
var m=today.getUTCMinutes();
var s=today.getUTCSeconds();
m = checkTime(m);
s = checkTime(s);
var formatted = h+":"+m+":"+s;
$('.serverTime').html(formatted);
}, 2000);
Here's the whole thing, with simulated server time:
function simulateServerTime() {
var time = new Date();
// Add 1 minute and 12 seconds to simulate the clocks being a little out of sync
time.setMinutes(time.getMinutes() + 1, 12);
// Reduce to seconds to simulate php
time = Math.round(time / 1000);
// Specify an offset of -6 hours
var offset = -6 * 60 * 60;
return (time + offset) * 1000;
}
var serverTime = simulateServerTime();
var localTime = new Date();
// Offset between the computer and the server
var timeDiff = serverTime - localTime;
// The ticking clock function
setInterval(function () {
var today = new Date(Date.now() + timeDiff);
var h=today.getUTCHours();
var m=today.getUTCMinutes();
var s=today.getUTCSeconds();
m = checkTime(m);
s = checkTime(s);
var formatted = h+":"+m+":"+s;
document.querySelector(".serverTime").innerHTML = formatted;
}, 1000);
// Helper function for leading 0's
function checkTime(i) {
if (i<10) {i = "0" + i}; // add zero in front of numbers < 10
return i;
}
<div class="serverTime"></div>
*Or, so says the documentation. Last week, my machine said -0700, which is the octal representation of -448. My time is neither 700 hours earlier than GMT, nor is it 448 hours earlier than GMT, it's 7 hours earlier. It annoys me that the documentation states that it is the time offset in hours, when really it's the time offset in ISO 8601 Format.
Timestamp is not include timezone offset. Everyone's unix time is a offset from Jan 1, 1970 in UTC
If you wish to display a server timezone in client, your PHP must provide a server timezone. And about client timezone, you can reference this .
Also, I like to using moment.js to handle date/time problems.
I just modified the client side javascript, using moment. Wish it's all you needed
<script type="text/javascript" src="//cdnjs.cloudflare.com/ajax/libs/moment.js/2.8.3/moment.min.js"></script>
<?php
date_default_timezone_set("Europe/Athens");
$serverTime = time() * 1000 ;
$timezone = date('O');
?>
<div id="result"></div>
<script>
var serverTime = <?php echo $serverTime;?>,
timezone = "<?php echo $timezone;?>",
timeDiff = serverTime - Date.now();
setInterval(function () {
result.innerHTML= moment().add(timeDiff).zone(timezone).format('HH:mm:ss Z') + "<br/>" + result.innerHTML ;
}, 2000);
</script>

Countdown timer using Moment js

I am making a countdown timer for an event page, i used moment js for this.
Here is fiddle for this.
I am calculating date difference between event date and current date (timestamp), then using "duration" method from moment js. But the time left is not coming as expected.
Expected - 00:30m:00s
Actual - 5h:59m:00s
Code :
<script>
$(document).ready(function(){
var eventTime = '1366549200';
var currentTime = '1366547400';
var time = eventTime - currentTime;
var duration = moment.duration(time*1000, 'milliseconds');
var interval = 1000;
setInterval(function(){
duration = moment.duration(duration.asMilliseconds() - interval, 'milliseconds');
$('.countdown').text(moment(duration.asMilliseconds()).format('H[h]:mm[m]:ss[s]'));
}, interval);
});
</script>
I read the momentjs documentation to figure out the problem, but no luck.
Thanks for your time.
Update :
I end up doing like this :
<script>
$(document).ready(function(){
var eventTime = '1366549200';
var currentTime = '1366547400';
var leftTime = eventTime - currentTime;//Now i am passing the left time from controller itself which handles timezone stuff (UTC), just to simply question i used harcoded values.
var duration = moment.duration(leftTime, 'seconds');
var interval = 1000;
setInterval(function(){
// Time Out check
if (duration.asSeconds() <= 0) {
clearInterval(intervalId);
window.location.reload(true); #skip the cache and reload the page from the server
}
//Otherwise
duration = moment.duration(duration.asSeconds() - 1, 'seconds');
$('.countdown').text(duration.days() + 'd:' + duration.hours()+ 'h:' + duration.minutes()+ 'm:' + duration.seconds() + 's');
}, interval);
});
</script>
JS Fiddle.
In the last statement you are converting the duration to time which also considers the timezone. I assume that your timezone is +530, so 5 hours and 30 minutes gets added to 30 minutes. You can do as given below.
var eventTime= 1366549200; // Timestamp - Sun, 21 Apr 2013 13:00:00 GMT
var currentTime = 1366547400; // Timestamp - Sun, 21 Apr 2013 12:30:00 GMT
var diffTime = eventTime - currentTime;
var duration = moment.duration(diffTime*1000, 'milliseconds');
var interval = 1000;
setInterval(function(){
duration = moment.duration(duration - interval, 'milliseconds');
$('.countdown').text(duration.hours() + ":" + duration.minutes() + ":" + duration.seconds())
}, interval);
Check out this plugin:
moment-countdown
moment-countdown is a tiny moment.js plugin that integrates with
Countdown.js. The file is here.
How it works?
//from then until now
moment("1982-5-25").countdown().toString(); //=> '30 years, 10 months, 14 days, 1 hour, 8 minutes, and 14 seconds'
//accepts a moment, JS Date, or anything parsable by the Date constructor
moment("1955-8-21").countdown("1982-5-25").toString(); //=> '26 years, 9 months, and 4 days'
//also works with the args flipped, like diff()
moment("1982-5-25").countdown("1955-8-21").toString(); //=> '26 years, 9 months, and 4 days'
//accepts all of countdown's options
moment().countdown("1982-5-25", countdown.MONTHS|countdown.WEEKS, NaN, 2).toString(); //=> '370 months, and 2.01 weeks'
Although I'm sure this won't be accepted as the answer to this very old question, I came here looking for a way to do this and this is how I solved the problem.
I created a demonstration here at codepen.io.
The Html:
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.13.0/moment.min.js" type="text/javascript"></script>
<script src="https://cdn.rawgit.com/mckamey/countdownjs/master/countdown.min.js" type="text/javascript"></script>
<script src="https://code.jquery.com/jquery-3.0.0.min.js" type="text/javascript"></script>
<div>
The time is now: <span class="now"></span>, a timer will go off <span class="duration"></span> at <span class="then"></span>
</div>
<div class="difference">The timer is set to go off <span></span></div>
<div class="countdown"></div>
The Javascript:
var now = moment(); // new Date().getTime();
var then = moment().add(60, 'seconds'); // new Date(now + 60 * 1000);
$(".now").text(moment(now).format('h:mm:ss a'));
$(".then").text(moment(then).format('h:mm:ss a'));
$(".duration").text(moment(now).to(then));
(function timerLoop() {
$(".difference > span").text(moment().to(then));
$(".countdown").text(countdown(then).toString());
requestAnimationFrame(timerLoop);
})();
Output:
The time is now: 5:29:35 pm, a timer will go off in a minute at 5:30:35 pm
The timer is set to go off in a minute
1 minute
Note: 2nd line above updates as per momentjs and 3rd line above updates as per countdownjs and all of this is animated at about ~60FPS because of requestAnimationFrame()
Code Snippet:
Alternatively you can just look at this code snippet:
var now = moment(); // new Date().getTime();
var then = moment().add(60, 'seconds'); // new Date(now + 60 * 1000);
$(".now").text(moment(now).format('h:mm:ss a'));
$(".then").text(moment(then).format('h:mm:ss a'));
$(".duration").text(moment(now).to(then));
(function timerLoop() {
$(".difference > span").text(moment().to(then));
$(".countdown").text(countdown(then).toString());
requestAnimationFrame(timerLoop);
})();
// CountdownJS: http://countdownjs.org/
// Rawgit: http://rawgit.com/
// MomentJS: http://momentjs.com/
// jQuery: https://jquery.com/
// Light reading about the requestAnimationFrame pattern:
// http://www.paulirish.com/2011/requestanimationframe-for-smart-animating/
// https://css-tricks.com/using-requestanimationframe/
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.13.0/moment.min.js" type="text/javascript"></script>
<script src="https://cdn.rawgit.com/mckamey/countdownjs/master/countdown.min.js" type="text/javascript"></script>
<script src="https://code.jquery.com/jquery-3.0.0.min.js" type="text/javascript"></script>
<div>
The time is now: <span class="now"></span>,
</div>
<div>
a timer will go off <span class="duration"></span> at <span class="then"></span>
</div>
<div class="difference">The timer is set to go off <span></span></div>
<div class="countdown"></div>
Requirements:
CountdownJS: http://countdownjs.org/ (And Rawgit to be able to use countdownjs)
MomentJS: http://momentjs.com/
requestAnimationFrame() - use this for animation rather than setInterval().
Optional Requirements:
jQuery: https://jquery.com/
Additionally here is some light reading about the requestAnimationFrame() pattern:
http://www.paulirish.com/2011/requestanimationframe-for-smart-animating/
https://css-tricks.com/using-requestanimationframe/
I found the requestAnimationFrame() pattern to be much a more elegant solution than the setInterval() pattern.
I thought I'd throw this out there too (no plugins). It counts down for 10 seconds into the future.
var countDownDate = moment().add(10, 'seconds');
var x = setInterval(function() {
diff = countDownDate.diff(moment());
if (diff <= 0) {
clearInterval(x);
// If the count down is finished, write some text
$('.countdown').text("EXPIRED");
} else
$('.countdown').text(moment.utc(diff).format("HH:mm:ss"));
}, 1000);
<script src="https://momentjs.com/downloads/moment.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<div class="countdown"></div>
Timezones. You have to deal with them, by using getTimezoneOffset() if you want your visitors from around the wolrd to get the same time.
Try this http://jsfiddle.net/cxyms/2/, it works for me, but I'm not sure will it work with other timezones.
var eventTimeStamp = '1366549200'; // Timestamp - Sun, 21 Apr 2013 13:00:00 GMT
var currentTimeStamp = '1366547400'; // Timestamp - Sun, 21 Apr 2013 12:30:00 GMT
var eventTime = new Date();
eventTime.setTime(366549200);
var Offset = new Date(eventTime.getTimezoneOffset()*60000)
var Diff = eventTimeStamp - currentTimeStamp + (Offset.getTime() / 2);
var duration = moment.duration(Diff, 'milliseconds');
var interval = 1000;
setInterval(function(){
duration = moment.duration(duration.asMilliseconds() - interval, 'milliseconds');
$('.countdown').text(moment(duration.asMilliseconds()).format('H[h]:mm[m]:ss[s]'));
}, interval);
The following also requires the moment-duration-format plugin:
$.fn.countdown = function ( options ) {
var $target = $(this);
var defaults = {
seconds: 0,
format: 'hh:mm:ss',
stopAtZero: true
};
var settings = $.extend(defaults, options);
var eventTime = Date.now() + ( settings.seconds * 1000 );
var diffTime = eventTime - Date.now();
var duration = moment.duration( diffTime, 'milliseconds' );
var interval = 0;
$target.text( duration.format( settings.format, { trim: false }) );
var counter = setInterval(function () {
$target.text( moment.duration( duration.asSeconds() - ++interval, 'seconds' ).format( settings.format, { trim: false }) );
if( settings.stopAtZero && interval >= settings.seconds ) clearInterval( counter );
}, 1000);
};
Usage example:
$('#someDiv').countdown({
seconds: 30*60,
format: 'mm:ss'
});
Here's my timer for 5 minutes:
var start = moment("5:00", "m:ss");
var seconds = start.minutes() * 60;
this.interval = setInterval(() => {
this.timerDisplay = start.subtract(1, "second").format("m:ss");
seconds--;
if (seconds === 0) clearInterval(this.interval);
}, 1000);
Here are some other solutions.
No need to use additional plugins.
Snippets down below uses .subtract API and requires moment 2.1.0+
Snippets are also available in here https://jsfiddle.net/traBolic/ku5cyrev/
Formatting with the .format API:
const duration = moment.duration(9, 's');
const intervalId = setInterval(() => {
duration.subtract(1, "s");
const inMilliseconds = duration.asMilliseconds();
// "mm:ss:SS" will include milliseconds
console.log(moment.utc(inMilliseconds).format("HH[h]:mm[m]:ss[s]"));
if (inMilliseconds !== 0) return;
clearInterval(intervalId);
console.warn("Times up!");
}, 1000);
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.27.0/moment.min.js"></script>
Manuel formatting by .hours, .minutes and .seconds API in a template string
const duration = moment.duration(9, 's');
const intervalId = setInterval(() => {
duration.subtract(1, "s");
console.log(`${duration.hours()}h:${duration.minutes()}m:${duration.seconds()}s`);
// `:${duration.milliseconds()}` to add milliseconds
if (duration.asMilliseconds() !== 0) return;
clearInterval(intervalId);
console.warn("Times up!");
}, 1000);
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.27.0/moment.min.js"></script>
This worked for me a mixture from the above answers.
const moment = require('moment');
require("moment-countdown");
let timeRemaining = 2330;
console.log('moment', moment(moment().add(timeRemaining, 'seconds')).countdown().toString());
You're not using react native or react so forgive me this isn't a solution for you. - since this is a 7 year old post I'm pretty sure you figured it out by now ;)
But I was looking for something similar for react-native and it led me to this SO question. Incase anyone else winds up down the same road I thought I'd share my
use-moment-countdown hook for react or react native: https://github.com/BrooklinJazz/use-moment-countdown.
For example you can make a 10 minute timer like so:
import React from 'react'
import { useCountdown } from 'use-moment-countdown'
const App = () => {
const {start, time} = useCountdown({m: 10})
return (
<div onClick={start}>
{time.format("hh:mm:ss")}
</div>
)
}
export default App

Categories

Resources