JavaScript set future date as today - javascript

I have the below script in our website which generates a countdown timer. The dateFuture is set to todays date at midnight. Is it possible to set this as the current date so that we don't have to change this every day?
Thank you.
var today = new Date();
dateFuture = new Date(2016, 11, 16, 23, 59, 59);
function GetCount() {
dateNow = new Date();
amount = dateFuture.getTime() - dateNow.getTime();
delete dateNow;
if(amount < 0) {
document.getElementById("countbox").innerHTML = "Now!";
} else {
days = 0;
hours = 0;
mins = 0;
secs = 0;
out = "";
amount = Math.floor(amount / 1000);
days=Math.floor(amount / 86400);
amount = amount % 86400;
hours = Math.floor(amount / 3600);
amount = amount % 3600;
mins = Math.floor(amount / 60);
amount = amount % 60;
secs = Math.floor(amount);
if(days != 0) {
out += days + " day" + ((days != 1) ? "s" : "") + ", ";
}
if(days != 0 || hours != 0) {
out += hours + " hour" + ((hours != 1) ? "s" : "") + ", ";
}
if(days != 0 || hours != 0 || mins != 0) {
out += mins + " minute" + ((mins != 1) ? "s" : "") + ", ";
}
out += secs + " seconds";
document.getElementById("countbox").innerHTML = out;
setTimeout("GetCount()", 1000);
}
}
window.onload = function() { GetCount(); }
<div id="countbox"></div>

You can manipulate the date by using setHours, setMinutes, setSeconds and setMilliseconds.
var dateFuture = new Date();
dateFuture.setHours(23);
dateFuture.setMinutes(59);
dateFuture.setSeconds(59);
dateFuture.setMilliseconds(999);

Related

Javascript time, pluralities 1 min vs 1 mins. Timer for time notification received

self.calcMessageAge = function calcMessageAge(fireDate){
var date = Date.parse(fireDate);
var now = new Date();
now = Date.now();
// in seconds
var diff = Math.abs(date - now)/1000;
if(diff < 60) {
return "1 min";
}else if(diff < (60*60) ) {
// minutes
return Math.floor(diff/60) + " mins";
} else if(diff < (60*60*24)) {
// hours
var hrs = Math.floor(diff/60/60) + " hours";
if(hrs !== "1 hours") {
return Math.floor(diff/60/60) + " hours";
} else {
return Math.floor(diff/60/60) + " hour";
}
} else if(diff < (60*60*24*7)) {
// days
var _day = Math.floor(diff/24/60/60) + " days";
if(_day !== "1 days") {
return Math.floor(diff/24/60/60) + " days";
} else {
return Math.floor(diff/24/60/60) + " day";
}
} else if(diff < (60*60*24*7*4)) {
// weeks
var _weeks = Math.floor(diff/7/24/60/60) + " weeks";
if(_weeks !== "1 weeks") {
return Math.floor(diff/7/24/60/60) + " weeks";
} else {
return Math.floor(diff/7/24/60/60) + " week";
}
} else {
var _months = Math.floor(diff/4/7/24/60/60) + " months";
if(_months !== "1 months") {
return Math.floor(diff/4/7/24/60/60) + " months";
} else {
return Math.floor(diff/4/7/24/60/60) + " month";
}
}
};
The Above method should return a string based on the time (fireDate) that a notification reached the UI.
String such as "1 min ago" or "1 day ago" then "2 mins ago" or "2 days ago"
I am receiving "1 min ago" correctly but at 60 seconds I get "1 mins" returned, This also happens with day(s).
Im thinking it has to do with the fact Im checking against 60seconds when it should be 59? Im really kinda stumped. Any help would be appreciated.
You can do it like this
const getDiffrence = fireDate => {
const date = new Date(fireDate).getTime();
let now = new Date().getTime();
const diff = Math.abs(date - now) / 1000
const min = Math.floor(diff/60) % 60 || ''
const h = Math.floor(diff/60/60) % 60 || ''
const day = Math.floor(diff/60/60/24) % 24 || ''
const week = Math.floor(diff/60/60/24/7)|| ''
const month = Math.floor(diff/4/7/24/60/60) || ''
return `${month ? month + 'months' : ''} ${week ? week + 'weeks' : ''} ${day ? day + 'days' : ''} ${day ? day + 'days' : ''} ${h ? h + 'hours' : ''} ${min ? min + 'mins' : ''} `.replace(/\b(1\D+?)s/g, '$1').trim()
}
console.log(getDiffrence('2017/02/27 18:22'))
console.log(getDiffrence(new Date().getTime() - 60 * 1000 - 5000))
The main part of this code is .replace(/\b(1\D+?)s/g, '$1')
this will replace all 1 anythings with 1 anything or evnen crazer at this after it .replace(/(0\D+?)s\s*/g, '') and you just have to create string like '1days 0hours 0minutes'
console.log('11mounths 1days 0hours 20minutes'.replace(/\b0\D+?s\s*/g, '').replace(/\b(1\D+?)s/g, '$1'))
var calcMessageAge = function(fireDate) {
var date = Date.parse(fireDate);
var now = Date.now();
// in seconds
var diff = Math.abs(date - now) / 1000;
var minute = 60;
var hour = 60 * minute;
var day = 24 * hour;
var week = 7 * day;
var month = 4 * week; // month is usually longer than 4 weeks but I let the same as in original code
var num;
var label;
if (diff > month) {
num = Math.floor(diff / month);
label = num + ' month' + (num > 1 ? 's': '');
} else if (diff > week) {
num = Math.floor(diff / week);
label = num + ' week' + (num > 1 ? 's': '');
} else if (diff > day) {
num = Math.floor(diff / day);
label = num + ' day' + (num > 1 ? 's': '');
} else if (diff > hour) {
num = Math.floor(diff / hour);
label = num + ' hour' + (num > 1 ? 's': '');
} else if (diff > minute) {
num = Math.floor(diff / minute);
label = num + ' min' + (num > 1 ? 's': '');
} else {
label = '1 min';
}
return label;
};
console.log(calcMessageAge('02-02-2017'));
console.log(calcMessageAge('01-01-2017 20:00'));
console.log(calcMessageAge(new Date(new Date().getTime() - 60 * 1000)));
console.log(calcMessageAge(new Date(new Date().getTime() - 59 * 1000)));
console.log(calcMessageAge(new Date(new Date().getTime() - 60 * 60 * 4 * 1000)));

Javascript Countdown to show/hide on specified days & hours

Hi I've been trying to take and work with some code that I can get partially working, I want a countdown that we can set an end time it counts down to (obvious is obvious out of the way), we also want to set it to show at only certain times of the day and only certain days of the week.
I've managed to get the below working so we can set a time of the day to show but I can't get it to work so it only shows on the certain specified days. Can anyone help please?
var countdownMessage = "This ends in";
var now = new Date();
var time = now.getTime(); // time now in milliseconds
var countdownEnd = new Date(now.getFullYear(), now.getMonth(), now.getDate(), 12, 59); // countdownEnd 0000 hrs
//////////////////////////* Countdown *///////////////////////////////
function getSeconds() {
var ft = countdownEnd.getTime() + 86400000; // add one day
var diff = ft - time;
diff = parseInt(diff / 1000);
if (diff > 86400) {
diff = diff - 86400
}
startTimer(diff);
}
var timeInSecs;
var ticker;
function startTimer(secs) {
timeInSecs = parseInt(secs);
ticker = setInterval("tick()", 1000);
tick(); // to start counter display right away
}
function tick() {
var secs = timeInSecs;
if (secs > 0) {
timeInSecs--;
} else {
clearInterval(ticker); // stop counting at zero
//getSeconds(); // and start again if required
}
var hours = Math.floor(secs / 3600);
secs %= 3600;
var mins = Math.floor(secs / 60);
secs %= 60;
var result = ((hours < 10) ? "0" : "") + hours + " hours " + ((mins < 10) ? "0" : "") + mins + " minutes " + ((secs < 10) ? "0" : "") + secs + " seconds";
document.getElementById("countdown").innerHTML = (countdownMessage) + " " + result;
}
///////////////* Display at certain time of the day *//////////////////
//gets the current time.
var d = new Date();
if (d.getHours() >= 7 && d.getHours() <= 15) {
$("#countdown").show();
} else {
$("#countdown").hide();
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<body onload="getSeconds()">
<span id="countdown" style="font-weight: bold;"></span>
</body>
[EDIT]
Just to add to this I tried changing part of the script to this but it didn't work:
$(function() {
$("#countdown").datepicker(
{ beforeShowDay: function(day) {
var day = day.getDay();
if (day == 1 || day == 2) {
//gets the current time.
var d = new Date();
if(d.getHours() >= 7 && d.getHours() <= 10 ){
$("#countdown").show();
}
else {
$("#countdown").hide();
}
} else {
$("#countdown").hide();
}
}
});
});
Whatever you did is all good except the setInterval part where you are passing the string value as setInterval("tick()", 1000) instead of a function reference as setInterval(tick, 1000)
Also, I have updated the code as below to check the specific day along with specific hours which you had,
var d = new Date();
var day = d.getDay();
if (day == 0 || day == 6) {
if (d.getHours() >= 0 && d.getHours() <= 8) {
$("#countdown").show();
} else {
$("#countdown").hide();
}
}
You can give a try below,
var countdownMessage = "This ends in";
var now = new Date();
var time = now.getTime(); // time now in milliseconds
var countdownEnd = new Date(now.getFullYear(), now.getMonth(), now.getDate(), 12, 59); // countdownEnd 0000 hrs
//////////////////////////* Countdown *///////////////////////////////
function getSeconds() {
var ft = countdownEnd.getTime() + 86400000; // add one day
var diff = ft - time;
diff = parseInt(diff / 1000);
if (diff > 86400) {
diff = diff - 86400
}
startTimer(diff);
}
var timeInSecs;
var ticker;
function startTimer(secs) {
timeInSecs = parseInt(secs);
ticker = setInterval(tick, 1000);
tick(); // to start counter display right away
}
function tick() {
var secs = timeInSecs;
if (secs > 0) {
timeInSecs--;
} else {
clearInterval(ticker); // stop counting at zero
//getSeconds(); // and start again if required
}
var hours = Math.floor(secs / 3600);
secs %= 3600;
var mins = Math.floor(secs / 60);
secs %= 60;
var result = ((hours < 10) ? "0" : "") + hours + " hours " + ((mins < 10) ? "0" : "") + mins + " minutes " + ((secs < 10) ? "0" : "") + secs + " seconds";
document.getElementById("countdown").innerHTML = (countdownMessage) + " " + result;
}
$("#countdown").hide();
///////////////* Display at certain time of the day *//////////////////
//gets the current time.
var d = new Date();
var day = d.getDay();
if (day == 0 || day == 6) {
if (d.getHours() >= 0 && d.getHours() <= 8) {
$("#countdown").show();
}
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<body onload="getSeconds()">
<span id="countdown" style="font-weight: bold;"></span>
</body>

How do i change this from 12-hours clock to 24-hours clock?

I'm trying to display opening hours on a website and I'm having trouble converting this to a 24-hours clock system - What do i change to make it happend?
Cut off code ^
var checkTime = function() {
var today = weekday[now.getDay()];
var timeDiv = document.getElementById('timeDiv');
var dayOfWeek = now.getDay();
var hour = now.getHours();
var minutes = now.getMinutes();
//add AM or PM
var suffix = hour >= 12 ? "PM" : "AM";
// add 0 to one digit minutes
if (minutes < 10) {
minutes = "0" + minutes
};
if ((dayOfWeek == 0 || dayOfWeek == 6) && hour >= 13 && hour <= 23) {
hour = ((hour + 11) % 12 + 1); //i.e. show 1:15 instead of 13:15
timeDiv.innerHTML = 'it\'s ' + today + ' ' + hour + ':' + minutes + suffix + ' - we\'re open!';
timeDiv.className = 'open';
} else if ((dayOfWeek == 3 || dayOfWeek == 4 || dayOfWeek == 5) && hour >= 16 && hour <= 23) {
hour = ((hour + 11) % 12 + 1);
timeDiv.innerHTML = 'it\'s ' + today + ' ' + hour + ':' + minutes + suffix + ' - we\'re open!';
timeDiv.className = 'open';
} else {
if (hour == 0 || hour > 12) {
hour = ((hour + 11) % 12 + 1); //i.e. show 1:15 instead of 13:15
}
timeDiv.innerHTML = 'It\'s ' + today + ' ' + hour + ':' + minutes + suffix + ' - we\'re closed!';
timeDiv.className = 'closed';
}
};
var currentDay = weekday[now.getDay()];
var currentDayID = "#" + currentDay; //gets todays weekday and turns it into id
$(currentDayID).toggleClass("today"); //hightlights today in the view hours modal popup
setInterval(checkTime, 1000);
checkTime();
Thanks in advance.
Try this...
// Pad leading zero if number is < 10
function padZero(i){
return i < 10
? "0" + i
: i;
}
// Construct time string
function formatTime(day, hours, minutes, suffix, state){
return "It's " + today + " " + padZero(hours) + ":" + padZero(minutes) + suffix + " - we're " + state + "!";
}
// Output time to screen
function checkTime() {
var today = weekday[now.getDay()];
var timeDiv = document.getElementById('timeDiv');
var dayOfWeek = now.getDay();
var hour = now.getHours();
var minutes = now.getMinutes();
//add AM or PM
//var suffix = hour >= 12 ? "PM" : "AM";
var suffix = "";
if ((dayOfWeek == 0 || dayOfWeek == 6) && hour >= 13 && hour <= 23) {
//hour = ((hour + 11) % 12 + 1); //i.e. show 1:15 instead of 13:15
timeDiv.innerHTML = formatTime(today, hour, minutes, suffix, "open");
timeDiv.className = 'open';
} else if ((dayOfWeek == 3 || dayOfWeek == 4 || dayOfWeek == 5) && hour >= 16 && hour <= 23) {
//hour = ((hour + 11) % 12 + 1);
timeDiv.innerHTML = formatTime(today, hour, minutes, suffix, "open");
timeDiv.className = 'open';
} else {
/*if (hour == 0 || hour > 12) {
hour = ((hour + 11) % 12 + 1); //i.e. show 1:15 instead of 13:15
}*/
timeDiv.innerHTML = formatTime(today, hour, minutes, suffix, "closed");
timeDiv.className = 'closed';
}
};
Changes:
commented out the 3 lines that convert 24h to 12h
set suffix to "" (you could remove it altogether if you want)
moved repeated building of time string to it's own function formatTime()
created padZero() function to make sure hours and minutes under 10 are padded with a leading '0'.

Countdown timer in javascript for each row of table in html

var count = Number(sessionStorage.getItem('count')) || 3600;
var counter = setInterval(timer, 1000); //1000 will run it every 1 second
function timer() {
count = count - 1;
sessionStorage.setItem('count', count)
if (count == -1) {
clearInterval(counter);
return;
}
var seconds = count % 60;
var minutes = Math.floor(count / 60);
var hours = Math.floor(minutes / 60);
minutes %= 60;
hours %= 60;
var time_str = hours + ":h " + minutes + ":m " + seconds + ":s";
//document.cookie = 'time_str = hours + ":h " + minutes + ":m " + seconds + ":s"; expires=Thu, 26 March 20:47:11 UTC; path=/'
Array.prototype.forEach.call(document.querySelectorAll('.timer'), function (el ) { el.innerHTML = time_str; });
}
Above is my javascript code for countdown timer. This works fine, but it doesn't stop after "0h:0m:0s" time. it start counting in negative.
Here's a modified version of your code that works for me:
var count = 5;
var counter = setInterval(hockeytimer, 1000);
function hockeytimer() {
count = count - 1;
sessionStorage.setItem('count', count);
if (count == -1) {
clearInterval(counter);
return;
}
var seconds = count % 60;
var minutes = Math.floor(count / 60);
var hours = Math.floor(minutes / 60);
minutes %= 60;
hours %= 60;
if (hours === 0 && minutes === 0 && seconds === 0 ) {
var table = document.getElementById("hockeyt");
while (table.rows.length > 0 ) {
table.deleteRow();
}
}
var time_str = hours + ":h " + minutes + ":m " + seconds + ":s";
var timerCells = document.querySelectorAll('.hockeytimer');
for (var i = 0; i < timerCells.length; i++) {
var timerCell = timerCells[i];
timerCell.innerHTML = time_str;
}
}
Demo: http://jsbin.com/ceboqi/1/edit?html,js,output

Javascript Countdown from 8am-9pm

I have a Javascript countdown from 12am to 9pm each day and then resets itself.
I want the countdown to go from 8am-9pm instead of 12am-9pm. I have been fiddling with this but I can't seem to make it work with a start time other than the defaulted 12am.
My question is how can I make the countdown from 8-21 hours instead of 0-21 hours?
Javascript:
if (document.getElementById('countdown')) {
pad = function(n, len) { // leading 0's
var s = n.toString();
return (new Array( (len - s.length + 1) ).join('0')) + s;
};
function countDown(){
var now = new Date();
if ( (now.getDay() >= 1) && (now.getDay() <= 7) ) { // Monday to Sunday
var target = 21; // 21:00hrs is the cut-off point
if (now.getHours() < target) { //
var hrs = (target - 1) - now.getHours();
if (hrs < 0) hrs = 0;
var mins = 59 - now.getMinutes();
if (mins < 0) mins = 0;
var secs = 59 - now.getSeconds();
if (secs < 0) secs = 0;
var str = pad(hrs, 2) + ':' + pad(mins, 2) + '.<small>' + pad(secs, 2) + '</small>';
document.getElementById('countdown').innerHTML = str;
}
else
$('.wereOpen').hide();
}
}
var timerRunning = setInterval('countDown()', 1000);
}
Website
I don't fully understand your question, but could you just add now.getHours() >= 7 to your if statement, i.e.
...
if (now.getHours() >= 7 && now.getHours() < target) {
...
} else {
$('.wereOpen').hide();
}
...
EDIT
In light of the comment, the following should work:
if (document.getElementById('countdown')) {
pad = function(n, len) { // leading 0's
var s = n.toString();
return (new Array( (len - s.length + 1) ).join('0')) + s;
};
function countDown(){
var now = new Date();
if ( (now.getDay() >= 1) && (now.getDay() <= 7) ) { // Monday to Sunday
var target = 21; // 21:00hrs is the cut-off point
var hours = now.getHours(); //get hours
if(hours < 8 || hours >= target) {
$('.wereOpen').hide();
return;
} else
$('.wereOpen').show();
var hrs = (target - 1) - hours;
if (hrs < 0) hrs = 0;
var mins = 59 - now.getMinutes();
if (mins < 0) mins = 0;
var secs = 59 - now.getSeconds();
if (secs < 0) secs = 0;
var str = pad(hrs, 2) + ':' + pad(mins, 2) + '.<small>' + pad(secs, 2) + '</small>';
document.getElementById('countdown').innerHTML = str;
}
}
var timerRunning = setInterval('countDown()', 1000);
}

Categories