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
Related
I am just after a bit of advice really relating to the Flipclock.js plugin.
I have written the following code with a fair amount of assistance to make the clock countdown every day, which as far as I can tell is working well as I have struggled like mad to find solid documentation online for daily timers doing what I desire.
This is for a daily timer to showcase expiry time for a free delivery threshold of 1500 hours, however at weekends this would not be the case. Is it possible to use a conditional to check to see if the current day is Saturday or Sunday, and if so, increase the hours accordingly to display total hours/minutes until 1500 on the Monday?
My last concern is that I am grabbing information based on UST. The UK is currently 1 hour offset, but it won't always be. Is the only feasible solution to use an if only statement and offset the hour based on the dates of daylight saving time - or is there a smoother solution?
Thanks for your help
var clock;
// Check if it is a weekend or not
var d = new Date();
var n = d.getDay();
if( n == 6 )
var deadlineHour = 15, offset = 2;
else if( n == 0)
var deadlineHour = 15, offset = 1;
else
var deadlineHour = 15, offset = 0;
$(document).ready(function() {
// Grab the current date
var currentDate = new Date();
if(currentDate.getHours() >= deadlineHour) {
offset = 1;
}
var opts = {
clockFace: 'HourlyCounter',
countdown: true,
callbacks: {
stop: function() {
clock.setTime(24 * 60 * 60);
clock.start();
}
}
};
opts.classes = {
active: 'flip-clock-active',
before: 'flip-clock-before',
divider: 'flip-clock-divider',
dot: 'flip-clock-dot',
label: 'flip-clock-label',
flip: 'flip',
play: 'play',
wrapper: 'flip-clock-small-wrapper',
};
var futureDate = new Date(
currentDate.getFullYear(),
currentDate.getMonth(),
currentDate.getDate() + offset,
deadlineHour
);
// Calculate the difference in seconds between the future and current date
var diff = futureDate.getTime() / 1000 - currentDate.getTime() / 1000;
// Instantiate a coutdown FlipClock
clock = $('.clock').FlipClock(diff, opts);
});
<script type='text/javascript' src='//code.jquery.com/jquery-1.10.1.js'></script>
<script type='text/javascript' src="http://flipclockjs.com/_themes/flipclockjs/js/flipclock/flipclock.js"></script>
<link rel="stylesheet" type="text/css" href="http://flipclockjs.com/_themes/flipclockjs/css/flipclock.css">
<br/><div class="clock"></div>
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>
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>
I was trying to round the moment.js time object to next nearest 30 minute interval. But looks my logic us wrong.
Ex:
10:13am -> 10:30am
11:45am -> 12:00pm
Here is my current code
start = moment();
minuteReminder = start.minute() % 30;
start.add(minuteReminder, 'minutes');
start.format("D YYYY, h:mm:ss a");
Edit 2021 : easiest solution
const start = moment('2018-12-08 09:42');
const remainder = 30 - (start.minute() % 30);
const dateTime = moment(start).add(remainder, "minutes").format("DD.MM.YYYY, h:mm:ss a");
console.log(dateTime);
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.20.1/moment.min.js"></script>
Million ways to do this. You don't need moment.js really. Anyway, here is one.
Based on #Volune and #Cabloo answers and comments, an updated version can look like:
function round(date, duration, method) {
return moment(Math[method]((+date) / (+duration)) * (+duration));
}
Which then can be used like:
var date = moment();
var roundedDate = round(date, moment.duration(15, "minutes"), "ceil");
A generic solution:
var ROUNDING = 30 * 60 * 1000; /*ms*/
start = moment();
start = moment(Math.ceil((+start) / ROUNDING) * ROUNDING);
start.format("D YYYY, h:mm:ss a");
You can change ROUNDING from 30 minutes to whatever you want, and change Math.ceil by Math.round or Math.floor if you want another way to round the value.
You could do it with two ifs:
// Current date
let now = moment();
// Getting hour and minute
let hour = now.hour();
let minute = now.minute();
// Rounding minute on 30 mins interval
if(minute <= 30) now.set({minute: 30});
if(minute > 30) now.set({hour: hour + 1, minute: 0});
You can do it by a simple if-else clause:
if(moment().minute()> 30){
var myTime = moment().minute(30).second(0);
} else {
var myTime = moment().minute(0).second(0);
}
For my case, I instead wanted something like
04-28-2021 20:00 => 04-28-2021 20:00
04-28-2021 20:30 => 04-28-2021 20:30
04-28-2021 20:11 => 04-28-2021 20:00
04-28-2021 20:35 => 04-28-2021 20:30
so the function below did the trick
function toNearest30Minutes(date) {
const start = moment(date)
let remainder: number
const elapse = start.minute() % 30
if (elapse === 0) {
return moment(date).format()
} else {
remainder = 30 - elapse
return moment(start).add(remainder, "minutes").format()
}
}
The function above is just an adaptation of #jtromans answer higher above
One-line solution
moment().add( moment().minute() > 30 && 1 , 'hours').minutes( moment().minute() <= 30 ? 30 : 0).format("hh:mm a")
Working exemple :
var min = moment().minute()
var dateTime = moment().add(min > 30 && 1 , 'hours').minutes(min <= 30 ? 30 : 0).format("hh:mm a")
console.log(dateTime);
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.20.1/moment.min.js"></script>
even though the question has been answered, I'd like to share my solution too.
var moment = require('moment');
const roundToNearestXXMinutes = (start, roundTo) => {
let remainder = roundTo - (start.minute()+ start.second()/60) % roundTo;
remainder = (remainder > roundTo/2) ? remainder = -roundTo + remainder : remainder;
const changedDate = moment(start).add(remainder, "minutes" ).seconds(0).format("DD.MM.YYYY HH:mm:ss");
}
roundToNearestXXMinutes(moment(), 15);
EDIT: Thanks to Ishmael Sibisi for pointing to a flaw in my code! :)
the code below rounds up the current time to the nearest 30 minutes and also flawlessly takes care of any trailing seconds
var moment = require('moment')
var main = Date.now() //2020-03-13T23:17:34+01:00
var mainFormat = moment(main)
var secs = mainFormat.second()
var justMinutes = mainFormat.subtract(secs, 'seconds')
var remainder = 30 - (justMinutes.minute() % 30);
var dateTime = moment(justMinutes).add(remainder, 'minutes')
var final = dateTime.format()
console.log(final)
//2020-03-13T23:20:00+01:00
I am struggling with Flipclock http://flipclockjs.com/ . I browsed their website but i can't find a hint on how to change the time.
What i want to do is set the time i want to display. The problem is the browser on some smart TV's have a problem at changing the timezone so i wanted to get the time from the server with php but i can't set the time. This is my code. I only found some examples with countdown but that is not helpfull at all. It just uses the local time and it doesnt change at all. Thank you all in advance.
// Here i get the unix time from the server in a hidden field
ServerTime = $('#my_time').val();
// FlipClock initialization
clock = $('.clock').FlipClock({
autoStart: false,
clockFace: 'TwentyFourHourClock'
});
var time = clock.getTime();
console.log(time);
clock.setTime(time + 3600);
clock.start();
As i found out that FlipClock plugin somehow doesn't work with setTime() so i changed the code somewhere else. This is my initialization code for generating the FlipClockJS plugin.
var clock;
var index = '';
$(document).ready(function() {
clock = $('.clock').FlipClock({
clockFace: 'TwentyFourHourClock'
});
});
The changes i did was in the file Flipclock.js . It's around the 1325 line. Search for getMilitaryTime
Original:
getMilitaryTime: function() {
var date = new Date();
var obj = this.digitize([
date.getHours(),
date.getMinutes(),
date.getSeconds()
]);
return obj;
},
Edited:
getMilitaryTime: function() {
var date = new Date();
/* The folowing code looks at my server time and if it's higher or smaller it adds so many hours it is missing */
var ServerTime = $('#my_time').val();
var d = new Date();
var n = d.getHours();
var diff = ServerTime - n;
/*****************************************************************/
var obj = this.digitize([
date.getHours()+(diff),
date.getMinutes(),
date.getSeconds()
]);
return obj;
},
// FlipClock initialization
var ServerTime = $('#my_time').val();
var d = new Date();
var n = d.getHours();
var diff = ServerTime - n;
clock = $('.clock').FlipClock(diff,{
clockFace: 'TwentyFourHourClock'
});
This should allow you to display your time without modifications to the source code.
use this 100% work
<script>
var date = new Date('2016-11-07 07:00:0 am');
clock = $('.clock').FlipClock(date, {
clockFace: 'DailyCounter',
countdown: true,
showSeconds: false
});
</script>
you can change the clockFace value as per your requirement.