Javascript Countdown - javascript

I'm trying to create a countdown.
Basically I have the time a client has placed an order (which is in dateTime format stored in db for eg. "2014-08-14 12:52:09") and I also have the time it takes to complete the order ( which is either in hours and minutes "1" 45", or just minutes "45").
I got a countdown script from the web and I'm having a bad time figuring out how to format both times so that the script understands.
I got this coming from db
Order time----> 12:52:09
expiry time ---> 45minutes
expiry time may sometimes including hours as well:
eg: expiry time ---> 1hour 45minutes.
the script I got from the web I enclosed inside a function at the moment:
JS:
function clockTicking(){
// set the date we're counting down to
var target_date = new Date("Aug 15, 2019").getTime();
// variables for time units
var days, hours, minutes, seconds;
// get tag element
// update the tag with id "countdown" every 1 second
setInterval(function () {
// find the amount of "seconds" between now and target
var current_date = new Date().getTime();
var seconds_left = (target_date - current_date) / 1000;
// do some time calculations
days = parseInt(seconds_left / 86400);
seconds_left = seconds_left % 86400;
hours = parseInt(seconds_left / 3600);
seconds_left = seconds_left % 3600;
minutes = parseInt(seconds_left / 60);
seconds = parseInt(seconds_left % 60);
// format countdown string + set tag value
$('.countdown').html(days + "d, " + hours + "h, "+ minutes + "m, " + seconds + "s");
}, 1000);
}
Any help will be greatly appreciated.

You can change the beginning of the script to this
function setTimer(hours, minutes, dateTime){
var date = new Date(dateTime);
date.setHours(date.getHours() + hours);
date.setMinutes(date.getMinutes() + minutes);
var target_date = date.getTime();
// rest of script
}
then just call it with setTimer(1,30, "2014 09 24 00:23") to set the count down relative to 2014-09-24 01:53
Check it out here: jsFiddle

I would like to recommend Moment.js for this (and just about any kind of date/time parsing). While writing your own function might seem tempting, there are often many things that need to be taken into account and it's simply not worth it.
Using Moment.js, what you're trying to achieve can be done like this:
function clockTicking(){
var target_date = moment('Aug 15, 2019', 'MMM DD, YYYY');
// update the tag with id "countdown" every 1 second
setInterval(function () {
var moment_diff = moment.duration(target_date.diff(moment()));
// format countdown string + set tag value
$('.countdown').html(moment_diff.days() + "d, " + moment_diff.hours() + "h, "+ moment_diff.minutes() + "m, " + moment_diff.seconds() + "s");
}, 1000);
}
Of course, keep in mind that this particular example is not correct because the difference is too large (it will only work if the difference is less than a month), but it shouldn't be a problem since you mentioned in your original post that the difference should usually be measured in hours, not years.

I'd really consider using:
http://momentjs.com/docs/
If you're doing a fair amount of date time handling.
However, it looks like you're having trouble converting your two time formats to the date time object?
var stripNonNumberics = function(string) {
return Number(string.replace(/\D/g, ''));
}
var target_date = "1hour 45minutes"; // or var target_date = "45minutes";
var split_date = target_date.split(' ');
var minutes;
// If it has hours
if (split_date[1]) {
minutes = stripNonNumberics(split_date[1]) + (stripNonNumberics(split_date[0]) * 60);
} else {
minutes = stripNonNumberics(split_date[0]);
}
console.log(new Date(new Date().getTime() + minutes*60000););

Related

How to add minutes and hours to a time string using jquery

I want to add 30 minutes and then one hour to my variable which i already have my own date
var initialDate = '10:00';
So
if (some condition){
// i add 30 minutes ->10:30
}elseif(another condition){
// i add 1hour ->11:00
}
I tried this but doesn't work
var initialDate = '10:00';
var theAdd = new Date(initialDate);
var finalDate = theAdd.setMinutes(theAdd.getMinutes() + 30);
If I understand you correctly, the following will help you.
You need to add momentjs dependency via script tag and you can Parse, validate, manipulate, and display dates in JavaScript.
You can find more documentation regarding this in momentjs website
console.log(moment.utc('10:00','hh:mm').add(1,'hour').format('hh:mm'));
console.log(moment.utc('10:00','hh:mm').add(30,'minutes').format('hh:mm'));
<script src="https://momentjs.com/downloads/moment-with-locales.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
var theAdd = new Date();
// Set Hours, minutes, secons and miliseconds
theAdd.setHours(10, 00, 00, 000);
if (some condition) {
// add 30 minutes --> 10:30
theAdd.setMinutes(theAdd.getMinutes() + 30);
}
elseif (some condition) {
// add 1 hour --> 11:00
theAdd.setHours(theAdd.getHours() + 1);
}
Then you print the var theAdd to obtain the date and time.
To obtain just the time:
theAdd.getHours() + ":" + theAdd.getMinutes();
This should do the job. Dates need a year and month in their constructor, and you have to specify larger units of time if you specify and smaller ones, so it needs a day as well. Also, you have to pass in the hours and minutes separately. See https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date.
var initialDate = '10:00';
var theAdd = new Date(1900,0,1,initialDate.split(":")[0],initialDate.split(":")[1]);
if(30 min condition){
theAdd.setMinutes(theAdd.getMinutes() + 30);
} else if (1 hour condition){
theAdd.setHours(theAdd.getHours() + 1);
}
console.log(theAdd.getHours()+":"+theAdd.getMinutes());
Here is a javascript function that will add minutes to hh:mm time string.
function addMinutes(timeString, addMinutes) {
if (!timeString.match(/^([0-9]|0[0-9]|1[0-9]|2[0-3]):[0-5][0-9]$/))
return null;
var timeSplit = timeString.split(':');
var hours = parseInt(timeSplit[0]);
var minutes = parseInt(timeSplit[1]) + parseInt(addMinutes);
hours += Math.floor(minutes / 60);
while (hours >= 24) {
hours -= 24;
}
minutes = minutes % 60;
return ('0' + hours).slice(-2) + ':' + ('0' +minutes).slice(-2);
}

Countdown inverted

anyone can help me? Example, I want a countdown timer but inverted, example:
I insert my date and hour in javascript or mysqL (doesn't matter) and it will count ..
Example: I inserted: 01/07/2015
today the counter will show: 1day 1hour 19min
If you don't want to use jquery then you can do something like this:
var startTime = +new Date("07/01/2015"); // m/d/Y gets timestamp in ms
var second = 1000;
var minute = second * 60;
var hour = minute * 60;
var day = hour * 24;
var element = document.getElementById('timer'); // target element for the timer
function countUp() {
// time between now and the start date
var time = Date.now() - startTime;
// days passed since start
var days = Math.floor(time / day);
time -= days * day;
// hours passed
var hours = Math.floor(time / hour);
time -= hours * hour;
// minutes passed
var minutes = Math.floor(time / minute);
// update element
element.innerHTML = days + 'day ' + hours + 'hour ' + minutes + 'min';
setTimeout(countUp, minute);
};
countUp();
<span id="timer"></span>
Since you want to use the jQuery Countdown plugin, you can just use it's built-in count up functionality. Take a look at the 'Count Up' tab of the jQuery Countdown page: http://keith-wood.name/countdown.html.
EDIT: Adding code example
$("#countdown").countdown({since: new Date(2015, 7-1, 1)});
#countdown {
float: left;
width: 240px;
}
<link href="http://keith-wood.name/css/jquery.countdown.css" rel="stylesheet"/>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="http://keith-wood.name/js/jquery.plugin.js"></script>
<script src="http://keith-wood.name/js/jquery.countdown.js"></script>
<span id="countdown">

Javascript new Date() - Get seconds until end of the day

Working on a javascript-canvas based clock (classic analog clock view), also displaying the current date below the clock.
I already have this code to get the current time in javascript:
// get current time
var date = new Date();
var hours = date.getHours();
var minutes = date.getMinutes();
var seconds = date.getSeconds();
hours = hours > 12 ? hours - 12 : hours;
var hour = hours + minutes / 60;
var minute = minutes + seconds / 60;
Works great, except that I don't know how to get the number in seconds until the end of the day, so I could run an ajax request at 00:00h to update the current date.
The question is, how to get easily the number in seconds until end of the day in javascript?
I plan to start a setTimeout()-function after the clock loaded with the number of seconds left, to update the date when needed.
I'm assuming the date you want to change is not from these values. You need to change it in some place not directly related to this clock?
I would suggest to add a function to check if the day has changed and include it when the clock is refreshed.
In any case, getting the seconds to the end of the day should be something like
var secondsUntilEndOfDate = ( (24*60*60) - ( (hours*60*60) + (minutes*60) + seconds ) );
Javascript:
var d = new Date();
var h = d.getHours();
var m = d.getMinutes();
var s = d.getSeconds();
var secondsUntilEndOfDate = (24*60*60) - (h*60*60) - (m*60) - s;
For GMT+0 it would be
const secondUntilEndOfTheDay = 86400 - Math.floor(new Date() / 1000) % 86400;

How to set a fixed time in JQuery time count down (which doesn't affect when page refreshes)?

Im using this jquery plugin for time count down in my web app. Please help me out to remain the count down time not beginning at first each time.I want to set the cont down for a month (30 days 24h 60min 60 sec).So every time i refresh count down should not be started from the beginning.Thnx
here is the script code to set the time
$('#counter').countdown({
timestamp : (new Date()).getTime() + 30*24*60*60*1000
});
Does everyone need the same end time? For example, if you want to launch your site on March 5, 2014 at 5 PM Eastern, then you want to set the launch time like so:
var ts = new Date(Date.UTC(2014, 2, 7, 22))
$('#counter').countdown({
timestamp : ts
});
Alternatively, if each user needs to see a unique countdown, then you want to persist the time in a cookie. For example, if I open the page 5 minutes after you open the page. Should the timer be 5 minutes apart? If yes, then use the cookie. If no and both of our timers should be the same, then pass to the counter the desired end date.
Note: UTC is set if timezones matter for you.
var today = new Date()
var enddate = new Date(2014,05,01)
function calcDate(date1,date2) {
var datadiff = Math.abs(date1 - date2) / 1000;
// calculate (and subtract) whole days
var days = Math.floor(datadiff / 86400);
datadiff -= days * 86400;
// calculate (and subtract) whole hours
var hours = Math.floor(datadiff / 3600) % 24;
datadiff -= hours * 3600;
// calculate (and subtract) whole minutes
var minutes = Math.floor(datadiff / 60) % 60;
datadiff -= minutes * 60;
// what's left is seconds
var seconds = Math.floor(datadiff % 60);
var message = " ";
message += days + " days " ;
message += hours + " hours ";
message += minutes + " minutes \n";
message += seconds + " seconds \n";
return message
}
a = calcDate(enddate,today);
alert(a);
If you need persistence, rather than creating a new date object in javascript, pass the date from the backend which should be saved the first time you start the countdown.
There are many ways to persist data. One way might to to store the date into a cookie.
function getCookie(name) {
var value = "; " + document.cookie;
var parts = value.split("; " + name + "=");
if (parts.length == 2) return parts.pop().split(";").shift();
}
date = getCookie('date');
if(!date) {
document.cookie="date=" + new Date().getTime() + 30*24*60*60*1000 + ";";
date = getCookie('date');
}
alert(date);
That should help you persist the date between browser refreshes, but only as long as the cookie lasts.

count down to multiple moments, how?

I'm creating a site for my neighbor who has a Christmas light show.
The show runs every year from 6 December till 1 January twice an evening: at 6.30pm and at 8.00pm.
We want to add a countdown on the website which says:
next show: 00:00:00 (hh:mm:ss)
But how do I do that. When I search for it on the web every one says that I have to use an API for a countdown.
But they just use one date to count down to, so I think I have to write one myself in JavaScript.
Can anyone help with that?
I guess I have to use many if/else statements, starting with "is the month 1, 12 or something else?", followed by "has it yet been 18.30?" (I want 24-hours) and "has it already been 20.00" and so on.
But is there a better way, because this seems a lot of work to me.
JavaScript has a built-in date object that makes dealing with dates and times a bit less manual:
MDN documentation for JavaScript's date object
If you supply no arguments to its constructor, it'll give you the current date (according to the end user's computer):
var now = new Date();
You can set it to a specific date by supplying the year, month (zero-indexed from January), day, and optionally hour, minute and second:
var now = new Date();
var first_show = new Date(now.getFullYear(), 11, 6, 18, 30);
You can use greater- and less-than comparisons on these date objects to check whether a date is after or before another:
var now = new Date();
var first_show = new Date(now.getFullYear(), 11, 6, 18, 30);
alert(now < first_show);// Alerts true (at date of writing)
So, you could:
Create date objects for the current date, and each show this year (and for the 1st Jan shows next year)
Loop through the show dates in chronological order, and
Use the first one that's greater than the current date as the basis for your countdown.
Note: you should use something server-side to set now with accurate parameters, instead of just relying on new Date(), because if the end-user's computer is set to the wrong time, it'll give the wrong result.
Here's an example that will count down for 4 hours starting now() :
<script type="text/javascript">
var limit = new Date(), element, interval;
limit.setHours(limit.getHours() + 4);
window.onload = function() {
element = document.getElementById("countdown");
interval = setInterval(function() {
var now = new Date();
if (now.getTime() >= limit.getTime()) {
clearInterval(interval);
return;
}
var diff = limit.getTime() - now.getTime();
var hours = parseInt(diff / (60 * 60 * 1000));
diff = diff % (60 * 60 * 1000);
minutes = parseInt(diff / (60 * 1000));
diff = diff % (60 * 1000);
seconds = parseInt(diff / 1000);
if (hours < 10) {
hours = "0" + hours;
}
if (minutes < 10) {
minutes = "0" + minutes;
}
if (seconds < 10) {
seconds = "0" + seconds;
}
miliseconds = diff % 1000;
miliseconds = miliseconds.toString().substring(0, 2);
element.innerHTML = hours + ":" + minutes + ":" + seconds + ":" + miliseconds;
}, 10);
}
See it live here

Categories