My webpage timenite.com/item-shop shows a countdown that resets every day at 5:30 AM IST, I want to make a similar page in the directory timenite.com/xx and set it to reset every week on Thursdays at 8:30 PM IST.
Below is the script of what is being used currently on the item-shop page, there were actually two script files but I have combined them into one, just in case.
Help would be appreciated, thank you.
(function ($) {
$.fn.countdown = function (options, callback) {
var settings = $.extend({
date: null,
offset: null,
day: 'Day',
days: 'Days',
hour: 'Hour',
hours: 'Hours',
minute: 'Minute',
minutes: 'Minutes',
second: 'Second',
seconds: 'Seconds'
}, options);
// Throw error if date is not set
if (!settings.date) {
$.error('Date is not defined.');
}
// Throw error if date is set incorectly
if (!Date.parse(settings.date)) {
$.error('Incorrect date format, it should look like this, 12/24/2012 12:00:00.');
}
// Save container
var container = this;
/**
* Change client's local date to match offset timezone
* #return {Object} Fixed Date object.
*/
var currentDate = function () {
// get client's current date
var date = new Date();
// turn date to utc
var utc = date.getTime() + (date.getTimezoneOffset() * 60000);
// set new Date object
var new_date = new Date(utc + (3600000*settings.offset));
return new_date;
};
/**
* Main countdown function that calculates everything
*/
function countdown () {
var target_date = new Date(settings.date), // set target date
current_date = currentDate(); // get fixed current date
// difference of dates
var difference = target_date - current_date;
// if difference is negative than it's pass the target date
if (difference < 0) {
// stop timer
clearInterval(interval);
if (callback && typeof callback === 'function') callback();
return;
}
// basic math variables
var _second = 1000,
_minute = _second * 60,
_hour = _minute * 60,
_day = _hour * 24;
// calculate dates
var days = Math.floor(difference / _day),
hours = Math.floor((difference % _day) / _hour),
minutes = Math.floor((difference % _hour) / _minute),
seconds = Math.floor((difference % _minute) / _second);
// based on the date change the refrence wording
var text_days = (days === 1) ? settings.day : settings.days,
text_hours = (hours === 1) ? settings.hour : settings.hours,
text_minutes = (minutes === 1) ? settings.minute : settings.minutes,
text_seconds = (seconds === 1) ? settings.second : settings.seconds;
// fix dates so that it will show two digets
days = (String(days).length >= 2) ? days : '0' + days;
hours = (String(hours).length >= 2) ? hours : '0' + hours;
minutes = (String(minutes).length >= 2) ? minutes : '0' + minutes;
seconds = (String(seconds).length >= 2) ? seconds : '0' + seconds;
// set to DOM
container.find('.days').text(days);
container.find('.hours').text(hours);
container.find('.minutes').text(minutes);
container.find('.seconds').text(seconds);
container.find('.days_text').text(text_days);
container.find('.hours_text').text(text_hours);
container.find('.minutes_text').text(text_minutes);
container.find('.seconds_text').text(text_seconds);
}
// start
var interval = setInterval(countdown, 1000);
};
})(jQuery);
$(".openNav").click(function() {
$("body").toggleClass("navOpen");
$("nav").toggleClass("open");
$(".wrapper").toggleClass("open");
$(this).toggleClass("open");
});
// Second File from here
var today = new Date();
var tomorrow = new Date(today);
tomorrow.setDate(today.getDate() + 1);
var day = tomorrow.getDate();
var month = tomorrow.getMonth() + 1;
var year = tomorrow.getFullYear();
var nextday = month + '/' + day + '/' + year + ' 00:00:00';
$('#example').countdown({
date: nextday,
day: 'Day',
days: 'Days'
}, function () {
day++;
});
Update - Figured it out, thanks to a guy I met on Discord.
var curday;
var secTime;
var ticker;
function getSeconds() {
var nowDate = new Date();
var dy = 4 ; //Sunday through Saturday, 0 to 6
var countertime = new Date(nowDate.getFullYear(),nowDate.getMonth(),nowDate.getDate(),20,30,0); //20 out of 24 hours = 8pm
var curtime = nowDate.getTime(); //current time
var atime = countertime.getTime(); //countdown time
var diff = parseInt((atime - curtime)/1000);
if (diff > 0) { curday = dy - nowDate.getDay() }
else { curday = dy - nowDate.getDay() -1 } //after countdown time
if (curday < 0) { curday += 7; } //already after countdown time, switch to next week
if (diff <= 0) { diff += (86400 * 7) }
startTimer (diff);
}
function startTimer(secs) {
secTime = parseInt(secs);
ticker = setInterval("tick()",1000);
tick(); //initial count display
}
function tick() {
var secs = secTime;
if (secs>0) {
secTime--;
}
else {
clearInterval(ticker);
getSeconds(); //start over
}
var days = Math.floor(secs/86400);
secs %= 86400;
var hours= Math.floor(secs/3600);
secs %= 3600;
var mins = Math.floor(secs/60);
secs %= 60;
//update the time display
document.getElementById("days").innerHTML = curday;
document.getElementById("hours").innerHTML = ((hours < 10 ) ? "0" : "" ) + hours;
document.getElementById("minutes").innerHTML = ( (mins < 10) ? "0" : "" ) + mins;
document.getElementById("seconds").innerHTML = ( (secs < 10) ? "0" : "" ) + secs;
if (curday == 1) {
document.getElementById("days_text").innerHTML = "Day"
}
}
Currently, it is working for 12am to 12am but I want it 2pm to 2pm. Is it possible?
setInterval(
function() {
var d = new Date();
var hours = 23 - d.getHours();
var min = 59 - d.getMinutes();
if ((min + '').length == 1) {
min = '0' + min;
}
var sec = 59 - d.getSeconds();
if ((sec + '').length == 1) {
sec = '0' + sec;
}
$('#the-final-countdown').html(hours + ':' + min + ':' + sec);
},
1000);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="the-final-countdown"></div>
setInterval(function time(){
var d = new Date();
if(d.getHours()<=13){
var hours = (13 - d.getHours());
}else{
var hours = (23+14 - d.getHours())
}
var min = 59 - d.getMinutes();
if((min + '').length == 1){
min = '0' + min;
}
var sec = 59 - d.getSeconds();
if((sec + '').length == 1){
sec = '0' + sec;
}
jQuery('#the-final-countdown p').html(hours+':'+min+':'+sec)
}, 1000);
A simple way to create a count down to 14:00 is to get the difference between now and the next time it will be 14:00, then convert to h:mm:ss, e.g.
// Returns milliseconds from date until next 1400
// Default for date is current time
function next1400(date) {
var now = date || new Date();
var end = new Date(now);
end.setHours(end.getHours() < 14? 14 : 38, 0, 0, 0);
return formatTime(end - now);
}
// Format milliseconds as H:mm:ss
function formatTime(ms) {
var s = Math.ceil(ms/1e3);
function z(n){return (n<10?'0':'')+n}
return (s/3.6e3 | 0) + ':' +
z((s%3.6e3)/60 | 0) + ':' +
z(s%60) ;
}
// QnD way to call each second. This will skip occasionally,
// there are better ways.
setInterval(function(){
console.log(next1400());
}, 1000);
I have a countdown script that enables me to see how much time there is left until a specific date and time in any given timezone. The script has improved alot from its original state (Much thanks to this community) but it still has some flaws.
The script is currently only able to countdown to a specific hour (Like 2015/12/12 18:00) but NOT to a specific minute (Like 2015/12/12 18:25).
I would like to be able to also specify any given minute of the hour (var minute), but I dont know how. Would greatly apreciate if anyone could help me out.
Edit: The timezone variable (var tz) must be taken into account.
Edit2: Solved the issue I got with the first answer, with this: toDate.setMinutes(minutes-(tz*60));
Full script below:
////////// CONFIGURE THE COUNTDOWN SCRIPT HERE //////////////////
var month = '11'; // '*' for next month, '0' for this month or 1 through 12 for the month
var day = '10'; // Offset for day of month day or + day
var hour = 14; // 0 through 23 for the hours of the day
var tz = -5; // Offset for your timezone in hours from UTC
var lab = 'tzcd'; // The id of the page entry where the timezone countdown is to show
function start() {displayTZCountDown(setTZCountDown(year,month,day,hour,tz),lab);}
// ** The start function can be changed if required **
window.onload = start;
////////// DO NOT EDIT PAST THIS LINE //////////////////
function setTZCountDown(year,month,day,hour,tz)
{
// props to Luke Woodward at Stackoverflow
var now = new Date();
var countdownToYear = now.getFullYear();
var countdownToMonth = now.getMonth();
var countdownToDay = now.getDate();
if (month === '*') {
countdownToMonth += 1;
} else if (month > 0) {
if (month <= now.getMonth()) {
countdownToYear += 1;
}
countdownToMonth = month - 1;
}
if (day.substr(0,1) === '+') {
var day1 = parseInt(day.substr(1), 10);
countdownToDay += day1;
} else {
countdownToDay = day;
}
var toDate = new Date(countdownToYear, countdownToMonth, countdownToDay);
// props to Luke Woodward at Stackoverflow^
toDate.setHours(hour);
toDate.setMinutes(0-(tz*60));
toDate.setSeconds(0);
var fromDate = new Date();
fromDate.setMinutes(fromDate.getMinutes() + fromDate.getTimezoneOffset());
var diffDate = new Date(0);
diffDate.setMilliseconds(toDate - fromDate);
return Math.floor(diffDate.valueOf()/1000);
}
function displayTZCountDown(countdown,tzcd)
{
if (countdown < 0) document.getElementById(tzcd).innerHTML = "<li>0<br><span class='tzcd-format'>day</span></li><li>0<br><span class='tzcd-format'>hours</span></li><li>0<br><span class='tzcd-format'>minutes</span></li><li>0<br><span class='tzcd-format'>seconds</span></li>";
else {var secs = countdown % 60;
if (secs < 10) secs = '0'+secs;
var countdown1 = (countdown - secs) / 60;
var mins = countdown1 % 60;
if (mins < 10) mins = '0'+mins;
countdown1 = (countdown1 - mins) / 60;
var hours = countdown1 % 24;
var days = (countdown1 - hours) / 24;
document.getElementById(tzcd).innerHTML = "<li>" + days + "<br><span class='tzcd-format'>day" + (days == 1 ? '' : 's') + '</span></li>' + "<li>" + hours + "<br><span class='tzcd-format'>hours</span></li> " + "<li>" + mins + "<br><span class='tzcd-format'>minutes</span></li>" +"<li>"+secs+ "<br><span class='tzcd-format'>seconds</span></li>";
setTimeout('displayTZCountDown('+(countdown-1)+',\''+tzcd+'\');',999);
}
}
I wasn't able to test it but this should be it:
////////// CONFIGURE THE COUNTDOWN SCRIPT HERE //////////////////
var month = '11'; // '*' for next month, '0' for this month or 1 through 12 for the month
var day = '10'; // Offset for day of month day or + day
var hour = 14; // 0 through 23 for the hours of the day
var tz = -5; // Offset for your timezone in hours from UTC
var minutes = '10';
var lab = 'tzcd'; // The id of the page entry where the timezone countdown is to show
function start() {displayTZCountDown(setTZCountDown(year,month,day,hour,tz),lab);}
// ** The start function can be changed if required **
window.onload = start;
////////// DO NOT EDIT PAST THIS LINE //////////////////
function setTZCountDown(year,month,day,hour,tz)
{
// props to Luke Woodward at Stackoverflow
var now = new Date();
var countdownToYear = now.getFullYear();
var countdownToMonth = now.getMonth();
var countdownToDay = now.getDate();
if (month === '*') {
countdownToMonth += 1;
} else if (month > 0) {
if (month <= now.getMonth()) {
countdownToYear += 1;
}
countdownToMonth = month - 1;
}
if (day.substr(0,1) === '+') {
var day1 = parseInt(day.substr(1), 10);
countdownToDay += day1;
} else {
countdownToDay = day;
}
var toDate = new Date(countdownToYear, countdownToMonth, countdownToDay);
// props to Luke Woodward at Stackoverflow^
toDate.setHours(hour);
toDate.setMinutes(minutes);
toDate.setSeconds(0);
var fromDate = new Date();
fromDate.setMinutes(fromDate.getMinutes() + fromDate.getTimezoneOffset());
var diffDate = new Date(0);
diffDate.setMilliseconds(toDate - fromDate);
return Math.floor(diffDate.valueOf()/1000);
}
function displayTZCountDown(countdown,tzcd)
{
if (countdown < 0) document.getElementById(tzcd).innerHTML = "<li>0<br><span class='tzcd-format'>day</span></li><li>0<br><span class='tzcd-format'>hours</span></li><li>0<br><span class='tzcd-format'>minutes</span></li><li>0<br><span class='tzcd-format'>seconds</span></li>";
else {var secs = countdown % 60;
if (secs < 10) secs = '0'+secs;
var countdown1 = (countdown - secs) / 60;
var mins = countdown1 % 60;
if (mins < 10) mins = '0'+mins;
countdown1 = (countdown1 - mins) / 60;
var hours = countdown1 % 24;
var days = (countdown1 - hours) / 24;
document.getElementById(tzcd).innerHTML = "<li>" + days + "<br><span class='tzcd-format'>day" + (days == 1 ? '' : 's') + '</span></li>' + "<li>" + hours + "<br><span class='tzcd-format'>hours</span></li> " + "<li>" + mins + "<br><span class='tzcd-format'>minutes</span></li>" +"<li>"+secs+ "<br><span class='tzcd-format'>seconds</span></li>";
setTimeout('displayTZCountDown('+(countdown-1)+',\''+tzcd+'\');',999);
}
}
I have two HTML input boxes, that need to calculate the time difference in JavaScript onBlur (since I need it in real time) and insert the result to new input box.
Format example: 10:00 & 12:30 need to give me: 02:30
Thanks!
Here is one possible solution:
function diff(start, end) {
start = start.split(":");
end = end.split(":");
var startDate = new Date(0, 0, 0, start[0], start[1], 0);
var endDate = new Date(0, 0, 0, end[0], end[1], 0);
var diff = endDate.getTime() - startDate.getTime();
var hours = Math.floor(diff / 1000 / 60 / 60);
diff -= hours * 1000 * 60 * 60;
var minutes = Math.floor(diff / 1000 / 60);
// If using time pickers with 24 hours format, add the below line get exact hours
if (hours < 0)
hours = hours + 24;
return (hours <= 9 ? "0" : "") + hours + ":" + (minutes <= 9 ? "0" : "") + minutes;
}
DEMO: http://jsfiddle.net/KQQqp/
Try This
var dif = ( new Date("1970-1-1 " + end-time) - new Date("1970-1-1 " + start-time) ) / 1000 / 60 / 60;
tl;dr
One off run
const t1 = new Date(1579876543210) // your initial time
const t2 = new Date(1579987654321) // your later time
const diff = t2-t1
const SEC = 1000, MIN = 60 * SEC, HRS = 60 * MIN
const humanDiff = `${Math.floor(diff/HRS)}:${Math.floor((diff%HRS)/MIN).toLocaleString('en-US', {minimumIntegerDigits: 2})}:${Math.floor((diff%MIN)/SEC).toLocaleString('en-US', {minimumIntegerDigits: 2})}.${Math.floor(diff % SEC).toLocaleString('en-US', {minimumIntegerDigits: 4, useGrouping: false})}`
console.log("humanDiff:", humanDiff)
// > humanDiff: 30:51:51.0111
As a function
function humanDiff (t1, t2) {
const diff = Math.max(t1,t2) - Math.min(t1,t2)
const SEC = 1000, MIN = 60 * SEC, HRS = 60 * MIN
const hrs = Math.floor(diff/HRS)
const min = Math.floor((diff%HRS)/MIN).toLocaleString('en-US', {minimumIntegerDigits: 2})
const sec = Math.floor((diff%MIN)/SEC).toLocaleString('en-US', {minimumIntegerDigits: 2})
const ms = Math.floor(diff % SEC).toLocaleString('en-US', {minimumIntegerDigits: 4, useGrouping: false})
return `${hrs}:${min}:${sec}.${ms}`
}
const t1 = new Date(1579876543210)
const t2 = new Date(1579987654321)
console.log("humanDiff(t1, t2):", humanDiff(t1, t2))
// > humanDiff: 30:51:51.0111
Explanation
Adjust humanDiff for your maximum and minimum reportable increments and formatting needs:
const t1 = new Date(1579876543210) // Set your initial time (`t1`)
const t2 = new Date(1579986654321) // , conclusion time (`t2`), and
const diff = t2-t1 // calculate their difference in milliseconds
console.log(" t2:", t2.toISOString()) // > t2: 2020-01-25T21:27:34.321Z
console.log(" t1:", t1.toISOString()) // > t1: 2020-01-24T14:35:43.210Z
console.log(" diff:", diff) // > diff: 111111111
// Set your constant time values for easy readability
const SEC = 1000
const MIN = 60 * SEC
const HRS = 60 * MIN
/* For a given unit
1) disregard any previously relevant units, e.g. to calculate minutes, we can
disregard all hours & focus on only the remainder - `(diff%HRS)`
2) divide the remainder by the given unit, e.g. for minutes, `(diff%HRS)/MIN`
3) disregard any remainder, e.g. again for minutes, `Math.floor((diff%HRS)/MIN)`
NOTE: for your maximum unit (HRS in the examples below) you probably _don't_
want to disregard high values, e.g. If the difference is >24 hrs and something,
you should either include a DAYS value, or simply display 30 hrs */
let hrs = Math.floor(diff/HRS)
let min = Math.floor((diff%HRS)/MIN)
let sec = Math.floor((diff%MIN)/SEC)
let ms = Math.floor(diff % SEC) // just the remainder
// BUT ms IS NOT ACTUALLY CORRECT, see humanDiff_3 for the fix ;-)
let humanDiff_1 = `${hrs}:${min}:${sec}.${ms}`
console.log("humanDiff_1:", humanDiff_1)
// > humanDiff_1: 30:51:51.111
sec = Math.round((diff%MIN)/SEC) // can also just round the last unit
const humanDiff_2 = `${hrs} hrs ${min} mins & ${sec} secs`
console.log("humanDiff_2:", humanDiff_2)
// > humanDiff_2: 30 hrs 51 mins & 51 secs
/* To ensure a set number of digits, format the numbers with `toLocaleString`'s
`minimumIntegerDigits`, if more than 3 digits, also use its `useGrouping` */
hrs = Math.floor(diff/HRS)
min = Math.floor((diff%HRS)/MIN).toLocaleString('en-US', {minimumIntegerDigits: 2})
sec = Math.floor((diff%MIN)/SEC).toLocaleString('en-US', {minimumIntegerDigits: 2})
ms = Math.floor(diff % SEC).toLocaleString('en-US', {minimumIntegerDigits: 4, useGrouping: false})
const humanDiff_3 = `${hrs}:${min}:${sec}.${ms}`
console.log("humanDiff_3:", humanDiff_3)
// > humanDiff_3: 30:51:51.0111
// NOTE: milliseconds are now 4 digits
This solution works for calculating diff between to separate military times
Example format: start = 23:00 / end = 02:30
function diff(start, end) {
start = start.split(":");
end = end.split(":");
if(Number(start[0]) > Number(end[0]) ) {
var num = Number(start[0])
var countTo = Number(end[0]);
var count = 0;
for (var i = 1; num != countTo;) {
num = num + i
if(num > 24) {
num = 0
}
count++
}
var hours = count - 1;
var startDate = new Date(0, 0, 0, start[0], start[1], 0);
var endDate = new Date(0, 0, 0, end[0], end[1], 0);
if(startDate.getMinutes() > endDate.getMinutes()) {
var hours = count - 2;
var diff = 60 - (startDate.getMinutes() - endDate.getMinutes());
} else {
var diff = endDate.getMinutes() - startDate.getMinutes();
}
var minutes = diff
} else {
var startDate = new Date(0, 0, 0, start[0], start[1], 0);
var endDate = new Date(0, 0, 0, end[0], end[1], 0);
var diff = endDate.getTime() - startDate.getTime();
var hours = Math.floor(diff / 1000 / 60 / 60);
diff -= hours * 1000 * 60 * 60;
var minutes = Math.floor(diff / 1000 / 60);
}
var returnValue = (hours < 9 ? "0" : "") + hours + ":" + (minutes < 9 ? "0" : "") + minutes
return returnValue;
}
Well this work almost great. Now use this code to calculate: 23:50 - 00:10 And see what you get.Or even 23:30 - 01:30. That's a mess.
Because getting the answer the other way in php is:
$date1 = strtotime($_POST['started']);
$date2 = strtotime($_POST['ended']);
$interval = $date2 - $date1;
$playedtime = $interval / 60;
But still, it works like yours.
I guess have to bring in the dates aswell?
And again: My hard research and development helped me.
if (isset($_POST['calculate'])) {
$d1 = $_POST['started'];
$d2 = $_POST['ended'];
if ($d2 < $d1) {
$date22 = date('Y-m-');
$date222 = date('d')-1;
$date2 = $date22."".$date222;
} else {
$date2 = date('Y-m-d');
}
$date1 = date('Y-m-d');
$start_time = strtotime($date2.' '.$d1);
$end_time = strtotime($date1.' '.$d2); // or use date('Y-m-d H:i:s') for current time
$playedtime = round(abs($start_time - $end_time) / 60,2);
}
And that's how you calculate time over to the next day.
//edit. First i had date1 jnd date2 switched. I need to -1 because this calculation only comes on next day and the first date vas yesterday.
After improving and a lot of brain power with my friend we came up to this:
$begin=mktime(substr($_GET["start"], 0,2),substr($_GET["start"], 2,2),0,1,2,2003);
$end=mktime(substr($_GET["end"], 0,2),substr($_GET["end"], 2,2),0,1,3,2003);
$outcome=($end-$begin)-date("Z");
$minutes=date("i",$outcome)+date("H",$outcome)*60; //Echo minutes only
$hours = date("H:i", $outcome); //Echo time in hours + minutes like 01:10 or something.
So you actually need only 4 lines of code to get your result. You can take only minutes or show full time (like difference is 02:32) 2 hours and 32 minutes.
What's most important: Still you can calculate overnight in 24 hour clock aka: Start time 11:50PM to let's say 01:00 AM (in 24 hour clock 23:50 - 01:00) because in 12 hour mode it works anyway.
What's most important: You don't have to format your input. You can use just plain 2300 as 23:00 input. This script will convert text field input to correct format by itself.
Last script uses standard html form with method="get" but you can convert it to use POST method as well.
This is an updated version of one that was already submitted. It is with the seconds.
function diff(start, end) {
start = start.split(":");
end = end.split(":");
var startDate = new Date(0, 0, 0, start[0], start[1], 0);
var endDate = new Date(0, 0, 0, end[0], end[1], 0);
var diff = endDate.getTime() - startDate.getTime();
var hours = Math.floor(diff / 1000 / 60 / 60);
diff -= hours * (1000 * 60 * 60);
var minutes = Math.floor(diff / 1000 / 60);
diff -= minutes * (1000 * 60);
var seconds = Math.floor(diff / 1000);
// If using time pickers with 24 hours format, add the below line get exact hours
if (hours < 0)
hours = hours + 24;
return (hours <= 9 ? "0" : "") + hours + ":" + (minutes <= 9 ? "0" : "") + minutes + (seconds<= 9 ? "0" : "") + seconds;
}
My Updated Version:
Allows for you to convert the dates into milliseconds and go off of that instead of splitting.
Example Does -- Years/Months/Weeks/Days/Hours/Minutes/Seconds
Example: https://jsfiddle.net/jff7ncyk/308/
With seconds you provided is not get result to me please find my updated function giving you the correct seconds here - By Dinesh J
function diff(start, end) {
start = start.split(":");
end = end.split(":");
var startDate = new Date(0, 0, 0, start[0], start[1],start[2], 0);
var endDate = new Date(0, 0, 0, end[0], end[1],end[2], 0);
var diff = endDate.getTime() - startDate.getTime();
var hours = Math.floor(diff / 1000 / 60 / 60);
diff -= hours * 1000 * 60 * 60;
var minutes = Math.floor(diff / 1000 / 60);
var seconds = Math.floor(diff / 1000)-120;
// If using time pickers with 24 hours format, add the below line get exact hours
if (hours < 0)
hours = hours + 24;
return (hours <= 9 ? "0" : "") + hours + ":" + (minutes <= 9 ? "0" : "") + minutes+ ":" + (seconds <= 9 ? "0" : "") + seconds;
}
Depending on what you allow to enter, this one will work. There may be some boundary issues if you want to allow 1am to 1pm
NOTE: This is NOT using a date objects or moment.js
function pad(num) {
return ("0"+num).slice(-2);
}
function diffTime(start,end) {
var s = start.split(":"), sMin = +s[1] + s[0]*60,
e = end.split(":"), eMin = +e[1] + e[0]*60,
diff = eMin-sMin;
if (diff<0) { sMin-=12*60; diff = eMin-sMin }
var h = Math.floor(diff / 60),
m = diff % 60;
return "" + pad(h) + ":" + pad(m);
}
document.getElementById('button').onclick=function() {
document.getElementById('delay').value=diffTime(
document.getElementById('timeOfCall').value,
document.getElementById('timeOfResponse').value
);
}
<input type="time" id="timeOfCall">
<input type="time" id="timeOfResponse">
<button type="button" id="button">CLICK</button>
<input type="time" id="delay">
calTimeDifference(){
this.start = dailyattendance.InTime.split(":");
this.end = dailyattendance.OutTime.split(":");
var time1 = ((parseInt(this.start[0]) * 60) + parseInt(this.start[1]))
var time2 = ((parseInt(this.end[0]) * 60) + parseInt(this.end[1]));
var time3 = ((time2 - time1) / 60);
var timeHr = parseInt(""+time3);
var timeMin = ((time2 - time1) % 60);
}
TimeCount = function()
{
t++;
var ms = t;
if (ms == 99)
{
s++;
t = 0;
if ( s == 60)
{
m++;
s = 0;
}
}
Dis_ms = checkTime(ms);
Dis_s = checkTime(s);
Dis_m = checkTime(m);
document.getElementById("time_val").innerHTML = Dis_m + ":" + Dis_s+ ":" + Dis_ms;
}
function checkTime(i)
{
if (i<10) {
i = "0" + i;
}
return i;
}
Try this: actually this a problem from codeeval.com
I solved it in this way .
This program takes a file as the argument so i used a little node js to read the file.
Here is my code.
var fs = require("fs");
fs.readFileSync(process.argv[2]).toString().split('\n').forEach(function (line) {
if (line !== "") {
var arr = line.split(" ");
var arr1 = arr[0].split(":");
var arr2 = arr[1].split(":");
var time1 = parseInt(arr1[0])*3600 + parseInt(arr1[1])*60 + parseInt(arr1[2]);
var time2 = parseInt(arr2[0])*3600 + parseInt(arr2[1])*60 + parseInt(arr2[2]);
var dif = Math.max(time1,time2) - Math.min(time1,time2);
var ans = [];
ans[0] = Math.floor(dif/3600);
if(ans[0]<10){ans[0] = "0"+ans[0]}
dif = dif%3600;
ans[1] = Math.floor(dif/60);
if(ans[1]<10){ans[1] = "0"+ans[1]}
ans[2] = dif%60;
if(ans[2]<10){ans[2] = "0"+ans[2]}
console.log(ans.join(":"));
}
});
We generally need time difference to estimate time taken by I/O operations, SP call etc, the simplest solution for NodeJs (the console is in callback- async execution) is following:
var startTime = new Date().getTime();
//This will give you current time in milliseconds since 1970-01-01
callYourExpectedFunction(param1, param2, function(err, result){
var endTime = new Date().getTime();
//This will give you current time in milliseconds since 1970-01-01
console.log(endTime - startTime)
//This will give you time taken in milliseconds by your function
if(err){
}
else{
}
})
I run the site for a radio show that airs every other Tuesday from 6 to 7am.
I'm trying to make a Javascript that will countdown the days, hours, minutes, and seconds till our show is live.
Then, when our show is live, I'd like to replace the countdown timer with an image using PHP. One hour later at 7am, our show is over; then I'd like the PHP script to return to the countdown timer.
I've tried to search around for countdown scripts that auto-update, but haven't found anything so far.
How would I make these scripts?
About a few hours ago i finished developing a javascript timer.
It should do the trick.
function miniTimer(s,callback,opt){
function getParam(value,defaultValue){
return typeof value == 'undefined' ? defaultValue : value;
}
this.s = getParam(s,0);
this.callback = getParam(callback,null);// a callback function that takes the current time in seconds as the first parameter and the formated time as the second
var opt = getParam(opt,{});
this.settings = {
masterCallback : getParam(opt.masterCallback,null),// same as above, but this one is called when the miniTimer finishes it's work (if maxPaceDuration or limitValue is set)
autoplay : getParam(opt.autoplay,false),
limitValue : getParam(opt.limitValue,null),
maxPaceCount : getParam(opt.maxPaceCount,null),
paceDuration : getParam(opt.paceDuration,1000),//milisec,
paceValue : getParam(opt.paceValue,1)//increment with only one second; set to -1 to countdown
};
this.interval = 0;
this.paceCount = 0;
if(this.settings.autoplay)
this.start();
return this;
}
miniTimer.prototype = {
toString : function(){
var d = Math.floor(this.s / (24 * 3600));
var h = Math.floor((this.s - d* 24 * 3600) / 3600);
var m = Math.floor((this.s - d* 24 * 3600 - h * 3600) / 60);
var s = this.s % 60;
if(h <= 9 && h >= 0)
h = "0"+h;
if(m <= 9 && m >= 0)
m = "0"+m;
if(s <= 9 && s >= 0)
s = "0"+s;
var day = d != 1 ? "days" : "day";
return d+" "+day+" "+h+":"+m+":"+s;
},
nextPace : function(){
if((this.settings.maxPaceCount != null && this.settings.maxPaceCount <= this.paceCount)
|| (this.settings.limitValue != null && this.settings.limitValue == this.s))
{
this.stop();
if(this.settings.masterCallback != null)
this.settings.masterCallback(this.s,this.toString());
return;
}
this.paceCount++;
var aux = this.s + this.settings.paceValue;
this.s += this.settings.paceValue;
if(this.callback != null)
this.callback(this.s,this.toString());
return this;
},
start : function(){
var $this = this;
this.interval = setInterval(function(){$this.nextPace();},this.settings.paceDuration);
return this;
},
stop : function(){
clearInterval(this.interval);
return this;
}
}
Now all you have to do is configure the proper callback function:
var el = document.getElementById('timer');
function getNextTuesday(){
var nextTuesday = new Date();
var t = nextTuesday.getDay();
t = t > 2 ? 9 - t : 2 - t;
nextTuesday.setDate(nextTuesday.getDate() + t);
return nextTuesday;
}
var showDuration = 2 * 60 * 60;//2h
var t = new miniTimer(Math.floor((getNextTuesday() - new Date())/1000),function(date,string){
if(date > 0)
el.innerHTML = string;
else
{
if(date <= -showDuration)
t.s = Math.floor((getNextTuesday() - new Date())/1000);
el.innerHTML = "<img src='http://t2.gstatic.com/images?q=tbn:ANd9GcT3CEVtaAYQJ4ALZRmgMHsCA8CG5tdpauLqSMhB66HJP_A0EDPPXw'>";
}
},{autoplay:true,paceValue : -1});
here's a working example : http://jsfiddle.net/gion_13/8wxLP/1/
You'll need to find the GMT time for 7am on the first tuesday the show is on,
and use new Date on the client to convert it to the user's local time.
Once you do that, it is like any other count down.
This example assumes EDT and April 5 for the first show.
(Date.UTC(2011, 3, 5, 11))
<!doctype html>
<html lang="en">
<head>
<meta charset= "utf-8">
<title>Small Page</title>
<script>
function counttoShow(){
var A= [], x, d, diff,cd=document.getElementById('countdown'),
cdimg=document.getElementById('onAir'),
onair= new Date(Date.UTC(2011, 3, 5, 11)), now= new Date();
while(onair<now) onair.setDate(onair.getDate()+14);
diff= (onair-now);
if(diff<3600000){
cdimg.style.visibility='visible';
cd.style.visibility='hidden';
}
else{
x= Math.abs(diff-3600000);
d= Math.floor(x/86400000);
if(d> 1){
A.push( d + " days");
x%= 86400000;
}
x= Math.floor(x/1000);
if(x> 3600){
d= Math.floor(x/3600);
A.push(d + " hour" +(d> 1? "s": ""));
x%= 3600;
}
if(x> 60){
d= Math.floor(x/60);
A.push(d + " minute" +(d> 1? "s": ""));
x%= 60;
}
if(x> 0) A.push(x + " second" +(x> 1? "s": ""));
cdimg.style.visibility='hidden';
cd.value= A.join(", ");
}
}
window.onload=function(){
var cdtimer=setInterval(counttoShow,1000);
document.body.ondblclick=function(){
if(cd.timer){
clearInterval(cdtimer);
cdtimer=null;
}
else cdtimer=setInterval(counttoShow,1000);
}
}
</script>
</head>
<body>
<h1>Radio Show</h1>
<p><img id="onAir" src="onair.gif">
<input id="countdown" type="text" size="40" readOnly style="border:none"> until show time.
</p>
</div>
</body>
</html>
This will get you the number of seconds until your next show (assuming your next show is tomorrow). Then you need to find the time from there.
var now = new Date(),
then = new Date( 2011, 3, 9 ),
diff = new Date();
diff.setTime( Math.abs( then.getTime() - now.getTime() ) );
diff.getTime();
From that point, you can set a timeout to run every second to recude the number of seconds displayed by 1, for example.
setTimeout( reduceSeconds );