I am trying to create a countdown timer where the user can input any combination of day, hour, minute, and seconds values and have it countdown to completion. I feel like I've got all the pieces but after a week of trying to solve this issue, I need help. I shuffle code around all with varying effects. Basically I feel like I'm missing a way to format the input data in a way I can use to subtract from the current date, but honestly I have no idea. Any input would be helpful.
Javascript:
function start() {
var countdownTimer = setInterval('timer()', 1000);
}
function timer() {
var d = parseInt(document.getElementById("days").value, 0);
var h = parseInt(document.getElementById("hours").value, 0);
var m = parseInt(document.getElementById("minutes").value, 0);
var s = parseInt(document.getElementById("seconds").value, 0);
var now = new Date();
var date = now.getTime();
addDay = now.setDate(now.getDate() + d);
addHour = now.setHours(now.getHours() + h);
addMinute = now.setMinutes(now.getMinutes() + m);
addSecond = now.setSeconds(now.getSeconds() + s);
var then = new Date(addHour + addMinute + addSecond);
if(d > 0 || h > 0 || m > 0 || s > 0){
var final = then - date;
var dd = Math.floor(final/ (1000 * 60 * 60 * 24));
var hh = Math.floor((final / (1000 * 60 * 60)) % 24);
var mm = Math.floor((final / 1000 / 60) % 60);
var ss = Math.floor((final / 1000) % 60);
document.getElementById("display").innerHTML = "Time Remaining: " + dd + "D " + hh + "H " + mm + "M " + ss + "S";
document.getElementById("message").innerHTML = then;
if (final < 0) {
clearInterval(countdownTimer);
document.getElementById("message").innerHTML = "Expired";
}
}else{
document.getElementById("display").innerHTML = " ";
document.getElementById("message").innerHTML = "Countdown Not Started";
}
}
HTML:
<div id="countdowntimer">
<button id="Start" onclick="start();">Start Timer</button>
D:<input type="text" id="days" value="0" />
H:<input type="text" id="hours" value="0" />
M:<input type="text" id="minutes" value="0" />
S:<input type="text" id="seconds" value="0" /><br>
<div id="display"></div>
<div id="message"></div>
</div>
If your timer is not based on date but on a given number of days, hours, minutes and seconds, why involve dates at all ? How about
function timer(){
var d = parseInt(document.getElementById("days").value, 0);
var h = parseInt(document.getElementById("hours").value, 0);
var m = parseInt(document.getElementById("minutes").value, 0);
var s = parseInt(document.getElementById("seconds").value, 0);
var current = ((d * 86400) + (h * 3600) + (m * 60) + s); //the current time left in seconds
if (current > 0) {
//take one second away, and rerender the seconds split into d, h, m, and s in the html, which you will reuse next time timer() runs
} else {
//expired
}
}
Related
I want to calculate my work time. It works fine when I input
08:00 - 09:00 = 01:00
But when I input this time
23:30 - 01:30 = 10:00
It should return 02:00
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">
I would use a Date object to calculate the difference in time. Since you are only interested in the time, you can use any date to construct a valid date string. The reason why you are getting 10 hours is because there is no date to show that it is 1am the following day (this is from my understanding of your question).
You can do something like below to get the job done.
const pad = num => (num < 10) ? `0${num}` : `${num}`;
const addADay = (start, end) => {
const sHour = parseInt(start.split(':')[0], 10);
const eHour = parseInt(end.split(':')[0], 10);
return (eHour < sHour);
};
const diffTime = (start, end) => {
const startDate = new Date(`2019/01/01 ${start}:00`);
const endDate = addADay(start, end)
? new Date(`2019/01/02 ${end}:00`)
: new Date(`2019/01/01 ${end}:00`);
const diff = endDate.getTime() - startDate.getTime();
const hours = Math.floor(diff / 3600000);
const min = (diff - (hours * 3600000)) / 60000;
return `${pad(hours)}:${pad(min)}`;
}
console.log(diffTime('08:00','09:00')); // returns 01:00
console.log(diffTime('23:00','01:30')); // returns 02:30
The most important part in the required algorithm is finding if the end date is tomorrow.
based on your code here is a working example with my suggestion.
<!DOCTYPE html>
<html>
<head>
<style>
</style>
</head>
<body>
<input type="time" id="timeOfCall">
<input type="time" id="timeOfResponse">
<button type="button" id="button" onclick="diffTime()">CLICK
</button>
<input type="time" id="delay">
<script>
function pad(num) {
return ("0" + num).slice(-2);
}
function diffTime() {
var start = document.getElementById("timeOfCall").value;
var end = document.getElementById("timeOfResponse").value;
// start date will be today
var d1 = new Date();
var s = start.split(":")
var date1 = new Date(d1.getFullYear(),d1.getMonth(),d1.getDate(),s[0],s[1],0,0);
var s2 = end.split(":")
// end date
if(s2[0] < s[0])
{
// its tommorow...
var ms = new Date().getTime() + 86400000;
var tomorrow = new Date(ms);
d1=tomorrow;
}
var date2 = new Date(d1.getFullYear(),d1.getMonth(),d1.getDate(),s2[0],s2[1],0,0);
var diff = date2.getTime() - date1.getTime();
var msec = diff;
var hh = Math.floor(msec / 1000 / 60 / 60);
msec -= hh * 1000 * 60 * 60;
var mm = Math.floor(msec / 1000 / 60);
msec -= mm * 1000 * 60;
var ss = Math.floor(msec / 1000);
msec -= ss * 1000;
alert(hh + ":" + mm + ":" + ss);
}
document.getElementById("timeOfCall").defaultValue = "23:30";
document.getElementById("timeOfResponse").defaultValue = "01:30";
</script>
</body>
</html>
Hello I have change your code slightly. The explanation is, let your start time is 10:00 and end time is 09:00. Now think with clock wise. the time had to go to 9:00 with 24 hours. So the calculation is difference between 24 and 10 hours and add the rest of the time.
D = E + (24 - S)
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) {
diff = eMin + (24 * 60 - sMin); /* You had to caculate with 24 hours */
}
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">
Here is another simpler way to look at the problem which satisfies all of your test cases, try your all test cases if any case fails then tell me i will fix it.
you just take the hours first and then check if is am or pm and then simply count the minutes.
function diffTime(start, end) {
var s = start.split(":");
var e = end.split(":");
var dHour;
var dMinute ;
var startHour = parseInt(s[0]);
var endHour = parseInt(e[0]);
var startMinute = parseInt(s[1]);
var endMinute = parseInt(e[1]);
// For counting difference of hours
if((startHour>12 && endHour>12) || (startHour<12 && endHour<12))
{
if(startHour<endHour)
{
dHour = endHour - startHour;
}
else if(startHour>endHour)
{
dHour = 24 - ( startHour - endHour);
}
else
{
dHour = 24;
}
}
else if(startHour>12 && endHour<=12)
{
dHour = (24 - startHour) + endHour;
}
else if(startHour<=12 && endHour > 12)
{
dHour = endHour - startHour;
}
else
{
dHour = 24
}
// For Counting Difference of Minute
if (startMinute>endMinute)
{
dMinute = 60 - (startMinute - endMinute);
dHour = dHour - 1;
}
else if(startMinute<endMinute)
{
dMinute = endMinute - startMinute;
}
else
{
dMinute = 0
}
return dHour + " Hours " + dMinute + " Minutes";
}
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="text" id="delay">
thank you friend i solve my problem, Miraz Chowdhury's code has done my job
function diff(t1, t2) {
const day = 86400000;
function pad(num) {
return ("0" + num).slice(-2);
}
let time1 = t1.split(":").map(el => parseInt(el));
let time2 = t2.split(":").map(el => parseInt(el));
let zero = (new Date(1990, 0, 1, 0, 0)).setMilliseconds(0)
let aaa = (new Date(1990, 0, 1, time1[0], time1[1])).setMilliseconds(0)
let bbb = (new Date(1990, 0, 1, time2[0], time2[1])).setMilliseconds(0)
let diff = day -Math.abs(aaa - bbb)<Math.abs(aaa - bbb)?day -Math.abs(aaa - bbb):Math.abs(aaa - bbb)
return `${pad(Math.round(diff/1000/60/60))}:${pad(Math.abs(Math.round(diff/1000/60%60)))}`;
}
console.log(diff("09:00", "08:00"));
console.log(diff("23:30", "01:30"));
console.log(diff("01:30", "23:30"));
I have My Code below,
Before=document.getElementsByName("beforehr[]");
After=document.getElementsByName("afterhr[]");
MonthTotal=0
for(i=0;i<Before.length;i++){
BeforeInSeconds= // Convert Before[i].value to Seconds
AfterInSeconds= // Convert After[i].value to Seconds
MonthTotal=parseInt(MonthTotal)+ parseInt(BeforeInSeconds)+parseInt(AfterInSeconds);
}
MonthTotalHRS= // Convert MonthTotal value to Time
document.getElementById("txtMonthTotal").value=MonthTotal;
document.getElementById("Mthtotal").innerHTML=MonthTotalHRS;
I need to convert the Before Hours to Seconds, After Hours to Seconds, sum All the Seconds and convert to Time and put it into Mthtotal
Assuming that variables Before and After are arrays.
var Before = [1, 2]; //180 Secs
var After = [3, 4]; // 420 Secs
var MonthTotal=0;
function secondsToHms(d) { // Function to convert Secs to H:m:s
d = Number(d);
var h = Math.floor(d / 3600);
var m = Math.floor(d % 3600 / 60);
var s = Math.floor(d % 3600 % 60);
var hDisplay = h > 0 ? h + (h == 1 ? " hour " : " hours ") : "";
var mDisplay = m > 0 ? m + (m == 1 ? " minute " : " minutes ") : "";
var sDisplay = s > 0 ? s + (s == 1 ? " second" : " seconds") : "";
return hDisplay + mDisplay + sDisplay;
}
for(i=0;i<Before.length;i++)
{
BeforeInSeconds= Before[i] * 60;
AfterInSeconds= After[i] * 60;
MonthTotal=parseInt(MonthTotal)+ parseInt(BeforeInSeconds)+parseInt(AfterInSeconds);
}
console.log(MonthTotal); //600 Secs
var convertedop=secondsToHms(MonthTotal);
alert(convertedop);
You can use .split(':') to split up your time format into an array. Where index 0 is the hour, index 1 is the minutes and index 2 is the seconds. You can then convert each time unit into seconds.
Hours to seconds: hour*3600
Minutes to seconds: minutes*60
Seconds to seconds: seconds*1 so just seconds
Doing all of this will give you your total result:
var before = [...document.getElementsByName("beforehr[]")];
var after = [...document.getElementsByName("afterhr[]")];
var monthTotal = 0
for (i = 0; i < before.length; i++) {
var beforeTime = before[i].value.split(':');
var afterTime = after[i].value.split(':');
var hourSeconds = +beforeTime[0] * 3600; // Convert the hours to seconds
var minuteSeconds = +beforeTime[1] * 60; // Convert the mins to secs
var seconds = +beforeTime[2]; // No conversions needed for secs to secs
var beforeInSeconds = hourSeconds + minuteSeconds + seconds;
// The above can be compresed into one line. I'll repeat the above for the afterTime on one line as an example:
var afterInSeconds = (+afterTime[0] * 3600) + (+afterTime[1] * 60) + (+afterTime[2])
monthTotal += parseInt(beforeInSeconds) + parseInt(afterInSeconds);
}
console.log("Month total in seconds", monthTotal)
// Hours, minutes and seconds (round down)
var hrs = ~~(monthTotal / 3600);
var mins = ~~((monthTotal % 3600) / 60);
var secs = ~~monthTotal % 60;
console.log("Month total in H:M:S", hrs +':' +mins + ':' + secs);
<input type="text" value="1:0:0" name="beforehr[]" />
<input type="text" value="1:0:0" name="beforehr[]" />
<br />
<input type="text" value="4:0:0" name="afterhr[]" />
<input type="text" value="4:0:0" name="afterhr[]" />
Also, note the unary + operator is similar to parseInt (it acts a little differently however).
The ~~ is simply just a fancy way of saying Math.floor(number)
Solution Simplified
<script>
function CalOt(){
Before=document.getElementsByName("beforehr[]");
After=document.getElementsByName("afterhr[]");
TodayOt=document.getElementsByName("txtTodayOt[]");
MonthTotal=0
for(i=0;i<Before.length;i++){
//alert(TimetoSec(Before[i].value));
BeforeInSeconds=TimetoSec(Before[i].value); //Convert Before[i].value to Seconds
AfterInSeconds=TimetoSec(After[i].value);//Convert After[i].value to Seconds
Daytot=parseInt(BeforeInSeconds)+parseInt(AfterInSeconds);
TodayOt[i].value=SecToTime(Daytot);
MonthTotal=parseInt(MonthTotal)+parseFloat(Daytot);
}
MonthTotalHRS=SecToTime(MonthTotal);// Convert MonthTotal value to Time
document.getElementById("txtMonthTotal").value=MonthTotal;
document.getElementById("Mthtotal").innerHTML=MonthTotalHRS;
}
function TimetoSec(Time){
TimeSplit=Time.split(":");
HoursSeconds=TimeSplit[0]*60*60;
Minutes=TimeSplit[1]*60;
TotalSec=parseFloat(HoursSeconds)+parseFloat(Minutes)+parseFloat(TimeSplit[2]);
console.log(TotalSec+"\n");
return TotalSec;
}
function SecToTime(Seconds){
Hr=Math.floor(Seconds/(60*60));
Mn=Seconds % (60*60);
Min=Math.floor(Mn/(60));
Sec=Mn % (60);
return Hr+":"+Min+":"+Sec;
}
</script>
I want to create countdown timer for hour,minute and second when a button click. This is my code so far.
HTMLcode
<div class="colomn" style="margin-right: 20px">
<button class="start" onclick="clock();">Start</button>
</div>
javascript function
<script>
var myTimer;
function clock() {
myTimer = setInterval(myClock, 1000);
var c = 5;
function myClock() {
document.getElementById("demo").innerHTML = --c;
if (c == 0) {
clearInterval(myTimer);
}
}
}
</script>
This is simple and not showing separate hour,min and sec. How can I apply this for count hour,min and sec. Please help me.
Working Code:
<!DOCTYPE HTML>
<html>
<body>
<p id="demo"></p>
<button onclick="countdownTimeStart()">Start Timer</button>
<script>
// Set the date we're counting down to
function countdownTimeStart(){
var countDownDate = new Date("Sep 25, 2025 15:00:00").getTime();
// Update the count down every 1 second
var x = setInterval(function() {
// Get todays date and time
var now = new Date().getTime();
// Find the distance between now an the count down date
var distance = countDownDate - now;
// Time calculations for days, hours, minutes and seconds
var hours = Math.floor((distance % (1000 * 60 * 60 * 24)) / (1000 * 60 * 60));
var minutes = Math.floor((distance % (1000 * 60 * 60)) / (1000 * 60));
var seconds = Math.floor((distance % (1000 * 60)) / 1000);
// Output the result in an element with id="demo"
document.getElementById("demo").innerHTML = hours + "h "
+ minutes + "m " + seconds + "s ";
// If the count down is over, write some text
if (distance < 0) {
clearInterval(x);
document.getElementById("demo").innerHTML = "EXPIRED";
}
}, 1000);
}
</script>
</body>
</html>
Simple Answer would be as follows,
html part,
<button onclick="clockStart()">Start</button>
<p id="demo"></p>
JS part,
function clockStart() {
setInterval(function() {
date = new Date()
let hour = date.getHours();
let minutes = date.getMinutes();
let seconds = date.getSeconds();
document.getElementById("demo").innerHTML = hour + ":"+ minutes + ":" + seconds;
}, 1000);
}
You need a counter for seconds. During each 1 second interval, decrement this counter, and do the necessary calculations.
var myTimer;
function clock() {
myTimer = setInterval(myClock, 1000);
var c = 3610; //Initially set to 1 hour
function myClock() {
--c
var seconds = c % 60; // Seconds that cannot be written in minutes
var secondsInMinutes = (c - seconds) / 60; // Gives the seconds that COULD be given in minutes
var minutes = secondsInMinutes % 60; // Minutes that cannot be written in hours
var hours = (secondsInMinutes - minutes) / 60;
// Now in hours, minutes and seconds, you have the time you need.
console.clear();
console.log(hours + ":" + minutes + ":" + seconds)
if (c == 0) {
clearInterval(myTimer);
}
}
}
clock();
Put it in a fiddle as well. See if it works..
EDIT: Updated the erroneous code. Thanks to #JDrake for pointing the fact out...
You can convert the value in seconds to one in hours, minutes, and seconds:
var secs = Math.floor(c % 60);
var mins = Math.floor((c/60) % 60);
var hours = Math.floor((c/(60*60)));
This will yield you the amount of seconds left over when removing the minutes (using the modulus operator) and then repeats this for the minutes and hours. You can also easily extend this to include days or weeks:
var hours = Math.floor((c/(60*60)) % 24);
var days = Math.floor((c/(60*60*24) % 7);
var weeks = Math.floor((c/60*60*24*7));
Your code does suffer from one downside: if for some reason the calls become slightly further apart, this might increasingly build a delay. You might instead want to use the lines:
endTime = Date.parse(new Date()) + delay;
timeLeft = endTime - Date.parse(new Date());
You can try this;
<script src="//ajax.googleapis.com/ajax/libs/jquery/3.1.0/jquery.min.js"></script>
<!-- This will start a timer for 5 hours 6 minutes and 7 seconds -->
<button onclick="countdown(5,6,7)"> Start </button>
<div><h3 id="timer"></h3></div>
<script>
function countdown(hr,mm,ss)
{
var interval = setInterval(function(){
if(hr == 0 && mm == 0 && ss == 0)clearInterval(interval);
ss--;
if(ss == 0)
{
ss = 59;
mm--;
if(mm == 0)
{
mm = 59;
hr--;
}
}
if(hr.toString().length < 2) hr = "0"+hr;
if(mm.toString().length < 2) mm = "0"+mm;
if(ss.toString().length < 2) ss = "0"+ss;
$("#timer").html(hr+" : "+mm+" : "+ss);
},1000)
}
</script>
Here is a very primordial clock for you:
function clock(t){
if(clock._stop){return};
var d = new Date(Date.now());
console.log(d.getHours()+":"+d.getMinutes()+":"+d.getSeconds()+":"+d.getMilliseconds())
window.requestAnimationFrame(clock);
}
clock._stop = false;
clock();
check your console. To stop the clock do clock._stop = true; To start it, set it back to false and call like clock(). You can wrap the logic inside an other object with getters/setters or whatever you prefer.
FIDDLE
var seconds_inputs = document.getElementsByClassName('deal_left_seconds');
var total_timers = seconds_inputs.length;
for ( var i = 0; i < total_timers; i++){
var str_seconds = 'seconds_'; var str_seconds_prod_id = 'seconds_prod_id_';
var seconds_prod_id = seconds_inputs[i].getAttribute('data-value');
var cal_seconds = seconds_inputs[i].getAttribute('value');
eval('var ' + str_seconds + seconds_prod_id + '= ' + cal_seconds + ';');
eval('var ' + str_seconds_prod_id + seconds_prod_id + '= ' + seconds_prod_id + ';');
}
function timer() {
for ( var i = 0; i < total_timers; i++) {
var seconds_prod_id = seconds_inputs[i].getAttribute('data-value');
var days = Math.floor(eval('seconds_'+seconds_prod_id) / 24 / 60 / 60);
var hoursLeft = Math.floor((eval('seconds_'+seconds_prod_id)) - (days * 86400));
var hours = Math.floor(hoursLeft / 3600);
var minutesLeft = Math.floor((hoursLeft) - (hours * 3600));
var minutes = Math.floor(minutesLeft / 60);
var remainingSeconds = eval('seconds_'+seconds_prod_id) % 60;
function pad(n) {
return (n < 10 ? "0" + n : n);
}
document.getElementById('deal_days_' + seconds_prod_id).innerHTML = pad(days);
document.getElementById('deal_hrs_' + seconds_prod_id).innerHTML = pad(hours);
document.getElementById('deal_min_' + seconds_prod_id).innerHTML = pad(minutes);
document.getElementById('deal_sec_' + seconds_prod_id).innerHTML = pad(remainingSeconds);
if (eval('seconds_'+ seconds_prod_id) == 0) {
clearInterval(countdownTimer);
document.getElementById('deal_days_' + seconds_prod_id).innerHTML = document.getElementById('deal_hrs_' + seconds_prod_id).innerHTML = document.getElementById('deal_min_' + seconds_prod_id).innerHTML = document.getElementById('deal_sec_' + seconds_prod_id).innerHTML = pad(0);
} else {
var value = eval('seconds_'+seconds_prod_id);
value--;
eval('seconds_' + seconds_prod_id + '= ' + value + ';');
}
}
}
var countdownTimer = setInterval('timer()', 1000);
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input type="hidden" class="deal_left_seconds" data-value="1" value="8888888">
<div class="box-wrapper">
<div class="date box"> <span class="key" id="deal_days_1">00</span> <span class="value">DAYS</span> </div>
</div>
<div class="box-wrapper">
<div class="hour box"> <span class="key" id="deal_hrs_1">00</span> <span class="value">HRS</span> </div>
</div>
<div class="box-wrapper">
<div class="minutes box"> <span class="key" id="deal_min_1">00</span> <span class="value">MINS</span> </div>
</div>
<div class="box-wrapper hidden-md">
<div class="seconds box"> <span class="key" id="deal_sec_1">00</span> <span class="value">SEC</span> </div>
</div>
<!DOCTYPE HTML>
<html>
<body>
<p id="demo"></p>
<button onclick="countdownTimeStart()">Start Timer</button>
<script>
// Set the date we're counting down to
function countdownTimeStart(){
var countDownDate = new Date("Sep 25, 2025 15:00:00").getTime();
// Update the count down every 1 second
var x = setInterval(function() {
// Get todays date and time
var now = new Date().getTime();
// Find the distance between now an the count down date
var distance = countDownDate - now;
// Time calculations for days, hours, minutes and seconds
var hours = Math.floor((distance % (1000 * 60 * 60 * 24)) / (1000 * 60 * 60));
var minutes = Math.floor((distance % (1000 * 60 * 60)) / (1000 * 60));
var seconds = Math.floor((distance % (1000 * 60)) / 1000);
// Output the result in an element with id="demo"
document.getElementById("demo").innerHTML = hours + "h "
+ minutes + "m " + seconds + "s ";
// If the count down is over, write some text
if (distance < 0) {
clearInterval(x);
document.getElementById("demo").innerHTML = "EXPIRED";
}
}, 1000);
}
</script>
</body>
</html>
I searched everywhere but I'm not satisfied by the answer. At last I'm posting here to get the answer.
I have two datepicker and time picker textbox which displays 12:00 format with AM & PM.
Here I want to calculate the TOTAL time which includes number of days and given time.
I want to add those time and display it in another text box. I need it in HH:MM format. I don't want seconds as my time picker textbox shows only HH:MM which is enough for me.
I tried many methods to add but i'm not getting the exact time value.
Below is my HTML code
<input type="date" id="opening_date">
<input type="date" id="closing_date">
<input type="time" class="time" id="garage_out_time">
<input type="time" class="time" id="garage_in_time">
<input type="text" id="total_hours">
Below is my script code
$(document).ready(function () {
function ConvertDateFormat(d, t) {
var dt = d.val().split('/');
return dt[0] + '/' + dt[1] + '/' + dt[2] + ' ' + t.val();
}
$(".time").change(function () {
var start = new Date(ConvertDateFormat($('#opening_date'), $('#garage_out_time')));
var end = new Date(ConvertDateFormat($('#closing_date'), $('#garage_in_time')));
console.log(start, end);
var diff = new Date(end - start);
var days = Math.floor(diff / 1000 / 60 / 60 / 24);
var hours = Math.floor((diff % (1000 * 60 * 60 * 24)) / 1000 / 60 / 60);
var total = (days * 24) + hours;
var startTime = document.getElementById("garage_out_time").value;
var endTime = document.getElementById("garage_in_time").value;
var s = startTime.split(':');
var e = endTime.split(':');
var endtime = parseInt(e[1], 10);
var starttime = parseInt(s[1], 10);
var min = endtime + starttime;
var minutes = min ;
var minhours = Math.floor(minutes / 60);
minutes = minutes % 60;
total = total + minhours;
if(minutes > 9){
$("#total_hours").val(total+":"+ minutes);
} else {
$("#total_hours").val(total+":0"+ minutes);
}
});
});
Above code is working for some extent BUT for example when I select 8:12 AM to 8:12 PM , the result I'm getting is 12:32 where answer should be 12:00.
I think you are over-complicating things somewhat. Your ConvertDateFormat() function already gives you what you need, so why are you parsing the time again? Try the code below (with thanks to this this answer)
var start = new Date(ConvertDateFormat($('#opening_date'), $('#garage_out_time')));
var end = new Date(ConvertDateFormat($('#closing_date'), $('#garage_in_time')));
console.log(start, end);
var diff = new Date(end - start);
var mins = Math.floor( diff / 60000 % 60 );
var hours = Math.floor( diff / 3600000 % 24 );
var days = Math.floor( diff / 86400000 );
console.log('days='+days+' hrs='+hours+' mins='+mins);
var totalHours = (days * 24) + hours;
var minsStr = (mins < 10) ? '0' + mins : mins;
$('#total_hours').val(totalHours + ':' + minsStr);
I am currently developing a website with a countdown timer at the headline: http://iphone.myhandykey.com/
The current timer is just 12hrs + few mins.. What I would like is the countdown timer will show the time remaining until 11PM on the Time Zone of the current visitor. Is that possible? Thanks!
Here is the JavaScript:
function startTimer(duration, display) {
var timer = duration, hours, minutes, seconds;
setInterval(function () {
hours = parseInt(((timer / 60) / 60 ) % 60, 10);
minutes = parseInt((timer / 60)%60, 10);
seconds = parseInt(timer % 60, 10);
hours = hours < 10 ? "0" + hours : hours;
minutes = minutes < 10 ? "0" + minutes : minutes;
seconds = seconds < 10 ? "0" + seconds : seconds;
display.textContent = hours + ":" + minutes + ":" + seconds;
if (--timer < 0) {
timer = duration;
}
}, 1000);
}
window.onload = function () {
var onehour = 60 * 600 * 1.231,
display = document.querySelector('#time');
startTimer(onehour, display);
};
Here is the HTML:
<span id=time></span>
EDIT: If the visitor's current time is for example 11:40pm, It should display 23hrs & 20mins left..
(function() {
var start = new Date;
start.setHours(23, 0, 0); // 11pm
function pad(num) {
return ("0" + parseInt(num)).substr(-2);
}
function tick() {
var now = new Date;
if (now > start) { // too late, go to tomorrow
start.setDate(start.getDate() + 1);
}
var remain = ((start - now) / 1000);
var hh = pad((remain / 60 / 60) % 60);
var mm = pad((remain / 60) % 60);
var ss = pad(remain % 60);
document.getElementById('time').innerHTML =
hh + ":" + mm + ":" + ss;
setTimeout(tick, 1000);
}
document.addEventListener('DOMContentLoaded', tick);
})();
Only <span id='time'></span> left!
Something like this:
$(document).ready(function () {
var mg = new Date(2016, 5, 21, 0, 0, 0, 0);
var tmr = window.setInterval(function () {
var d = new Date();
var dif = mg - d;
var s = parseInt(dif / 1000);
if (s < 0) {
document.getElementById('spCnt').innerHTML = 'Event starts';
window.clearInterval(tmr);
return;
}
var sec = s % 60;
var m = parseInt(s / 60);
var min = m % 60;
var h = parseInt(m / 60);
var hour = h % 24;
d = parseInt(h / 24);
document.getElementById('spCnt').innerHTML = d + ' days ' + hour + ' hours ' + min + ' min and ' + sec + ' sec remaining';
}, 1000);
});