setting custom time in flipclock plugin - javascript

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.

Related

Daily Timer to Exempt Days and Allow for DST in UK - FlipClock.js

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>

Javascript's date object toLocaleTimeString adds an hour

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>

How to reinit timer when it end?

everyone! On a website I use this timer, but I do not understand what I need to do when it end. When timer are end it should restart for next 14 days.
You may advice some books, where I can read about my problem or just aboud Date() in js.
Thanks!
There is a callback option for this plugin that is called as soon as you timer ends:
$('#countdown').timeTo({
timeTo: new Date(new Date('Sat Apr 25 2015 09:00:00 GMT+0200')),
displayDays: 2,
theme: "black",
displayCaptions: true,
fontSize: 48,
captionSize: 14,
// important part
callback: function(){
alert('Timer ended');
}
});
When you want to keep track of an user's exprieing time localStorage-API can be used to accomplish this.
Start expiring Timer:
Make a function to keep track of user's expiring date by using localStorage.This function returns the start date when an user visited your site the very first time. This date is used to determine whether an user has already extended the expire time of 14 days but further details are listed below:
function handleUserDate(expireInDays){
var now = new Date();
var startDate = localStorage.getItem('timerStartDate');
// has user already visited your site?
if(startDate){
// is user'date expired?
startDate = new Date(Number(startDate));
var futureDate = new Date(startDate.getTime()+expireInDays*(1000*60*60*24));
if(now.getTime() < futureDate.getTime()){
console.log('in future');
return startDate;
}
}
console.log('in past');
localStorage.setItem('timerStartDate', now.getTime());
return now;
}
Next function is used to activate a timer and putting the number of days that are left into the timeTo option:
function startTimer(inDays){
var now = new Date();
var futureDate = new Date(now.getTime()+inDays*(1000*60*60*24));
console.log(futureDate);
$('#countdown').timeTo({
timeTo: futureDate,
displayDays: 2,
theme: "black",
displayCaptions: true,
fontSize: 48,
captionSize: 14,
callback: function(){
alert('Timer ended');
var daysInFuture = 14;
startTimer(daysInFuture);
}
});
}
A Function to calculate the time difference in days between start date and now:
function getTimeDiff(date, date2, diff){
return Math.abs(date.getTime()-date2.getTime())/diff;
}
Put it all together:
var expireinDays = 14;// 14 day max
var startDate = handleUserDate(expireinDays);
console.log(startDate);// returns date of the very first time or when already expired it returns current date
var now = new Date();
var dayInMill = 1000*60*60*24;
var dayDifference = getTimeDiff(startDate,now,dayInMill);
dayDifference = expireinDays - dayDifference;
console.log(dayDifference); // days left
startTimer(dayDifference); // show timer

Count down from a particular date using flipclock.js

I am using http://flipclockjs.com/
This is my call script so far,
<script type="text/javascript">
var clock = $('.clock').FlipClock(3600 * 24 * 5, {
clockFace: 'DailyCounter',
countdown: true,
});
</script>
Please could someone tell me how i can count down from an exact date?
So for example the date is 21st July, 2014 in UK time, and everyone that visits that site will see how long there is remaining till that date based on the current date.
This is what I use
<div class="clock"></div>
<script type="text/javascript">
var date = new Date(2015, 6, 21);
var now = new Date();
var diff = (date.getTime()/1000) - (now.getTime()/1000);
var clock = $('.clock').FlipClock(diff,{
clockFace: 'DailyCounter',
countdown: true
});
</script>
Months is zero-based, so July, being the seventh month, uses 6.
#Matt, Great example, however I can see why "coolshrimp" posted a similar formula, both are half correct.
In my website, when i use jsfiddle, I want it to also show "Hours" "Minutes" and "Seconds", the following example worked perfectly for me:
<script type="text/javascript">
var date = new Date("February 01, 2016 02:15:00"); //Month Days, Year HH:MM:SS
var now = new Date();
var diff = (date.getTime()/1000) - (now.getTime()/1000);
var clock = $('.clock').FlipClock(diff,{
clockFace: 'DailyCounter',
countdown: true
});
</script>
Simple:
<div class="clock"></div>
<script type="text/javascript">
var clock = $('.clock').FlipClock(new Date("August 15, 2015 03:24:00"),{
clockFace: 'DailyCounter',
countdown: true
});
</script>
OR
<div class="clock"></div>
<script type="text/javascript">
var clock = $('.clock').FlipClock(new Date(2015,8,15),{
clockFace: 'DailyCounter',
countdown: true
});
</script>
You would have to do it someway like this:
$(document).ready(function(){
var date = new Date(2014, 7, 21, 0,0,0,0);
var today = new Date();
var dif = date.getTime() - today.getTime();
var timeLeft = Math.abs(dif/1000)/60;
var clock = $('.clock').FlipClock({
autoStart: false,
clockFace: 'DailyCounter',
countdown: true
});
clock.setTime(timeLeft);
clock.start();
});
The time function is a little bit off, so you'll have to play around with it to get it right.
Fiddle: http://jsfiddle.net/Uscg9/4/
I think using the api function of Date will be better (reference)
$(document).ready(function() {
// Today's date object.
var today = new Date();
today = today.getTime()/1000;
// Final date object.
var finalDate = new Date();
// Setting year for final date.
finalDate.setFullYear(2016);
// Setting month for final date.
// Month counting starts from 0 i.e. Jan = 0, therefore March = 2.
finalDate.setMonth(2);
// Setting Day for final date.
finalDate.setDate(17);
// Setting Hours for final date.
finalDate.setHours(12);
// Setting Minutes for final date.
finalDate.setMinutes(00);
// Setting Seconds for final date.
finalDate.setSeconds(00);
var finalDate = finalDate.getTime()/1000;
var diff = finalDate - today;
$('div#countdown-clock').FlipClock(diff, {
clockFace: 'HourlyCounter',
countdown: true
});
});
You need to calculate the diff yourself. See the example for counting down to new year:
https://github.com/objectivehtml/FlipClock/blob/master/examples/countdown-from-new-years.html
$(document).ready(function() {
// Grab the current date
var currentDate = new Date();
// Set some date in the past. In this case, it's always been since Jan 1
var pastDate = new Date(currentDate.getFullYear(), 0, 1);
// Calculate the difference in seconds between the future and current date
var diff = currentDate.getTime() / 1000 - pastDate.getTime() / 1000;
// Instantiate a coutdown FlipClock
clock = $('.clock').FlipClock(diff, {
clockFace: 'DailyCounter'
});
);

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