JavaScript Settimeout bug - javascript

I have some JavaScript code that looks like:
<script>
// For todays date;
var today = new Date();
var time = today.getHours() + ":" + today.getMinutes() + ":" + today.getSeconds();
var n = time;
var start = '6:56:00'
var end = '7:09:59'
setTimeout(function run(){
console.log()
if (n >= start && n < end)
{
window.location.href = "localhost/template/script2.html";
} else
{
location.reload(true);
}
console.log(run, 1000);
}, 1000);
</script>
I want the program to run only at 6:56:00 - 7:09:59
but it runs at 6:05:00 - 6:19:59 and 6:56:00 - 7:09:59 What should I do?

You're comparing strings when you should be comparing integers or date objects.

you must compare Date object. so you must use Date.parse
console.log(Date.parse('01/01/0001 10:20:45') > Date.parse('01/01/0001 5:10:10'))
// For todays date;
var today = new Date();
var time = today.getHours() + ":" + today.getMinutes() + ":" + today.getSeconds();
var n = time;
var start = '6:56:00'
var end = '7:09:59'
setTimeout(function run(){
console.log()
if (Date.parse("01/01/0001 " +n) >= Date.parse("01/01/0001 " + start) && n < Date.parse("01/01/0001 "+end))
{
window.location.href = "localhost/template/script2.html";
} else
{
location.reload(true);
}
console.log(run, 1000);
}, 1000);

Related

Getting issue while calculating the time difference using JavaScript

I am facing some issue while calculating the time difference between two dates using the JavaScript. I am providing my code below.
Here I have cutoff time and dep_time value. I have to calculate today's date with dep_date and if today's date and time is before the cutoff time then it will return true otherwise false. In my case its working fine in Chrome but for same function it's not working in Firefox. I need it to work for all browsers.
function checkform() {
var dep_date = $("#dep_date1").val(); //07/27/2019
var cut_offtime = $("#cutoff_time").val(); //1
var dep_time = $("#dep_time").val(); //6:00pm
var dep_time1 = dep_time.replace(/[ap]/, " $&");
var todayDate = new Date();
var todayMonth = todayDate.getMonth() + 1;
var todayDay = todayDate.getDate();
var todayYear = todayDate.getFullYear();
if (todayDay < 10) {
todayDay = "0" + todayDay;
}
if (todayMonth < 10) {
todayMonth = "0" + todayMonth;
}
//console.log('both dates',todayMonth,todayDay,todayYear);
var todayDateText = todayMonth + "-" + todayDay + "-" + todayYear;
var inputToDate = Date.parse(dep_date.replace(/\//g, " "));
var todayToDate = Date.parse(todayDateText.replace(/-/g, " "));
console.log("both dates", dep_date, todayDateText);
if (inputToDate >= todayToDate) {
var date = new Date();
var hours = date.getHours();
var minutes = date.getMinutes();
var ampm = hours >= 12 ? "pm" : "am";
hours = hours % 12;
hours = hours ? hours : 12; // the hour '0' should be '12'
minutes = minutes < 10 ? "0" + minutes : minutes;
var strTime = hours + ":" + minutes + " " + ampm;
var timeStart = new Date(todayDateText + " " + strTime);
var timeEnd = new Date(dep_date + " " + dep_time1);
var diff = (timeEnd - timeStart) / 60000; //dividing by seconds and milliseconds
var minutes = diff % 60;
var hours = (diff - minutes) / 60;
console.log("hr", hours);
if (parseInt(hours) > parseInt(cut_offtime)) {
return true;
} else {
alert("You should book this trip before " + cut_offtime + " hr");
return false;
}
} else {
alert("You should book this trip before " + cut_offtime + " hr");
return false;
}
}
Part of your issue is here:
var todayDateText = todayMonth + "-" + todayDay + "-" + todayYear;
var inputToDate = Date.parse(dep_date.replace(/\//g, " "));
The first line generates a string like "07-17-2019". The next changes it to "07 17 2019" and gives it to the built–in parser. That string is not a format supported by ECMA-262 so parsing is implementation dependent.
Chrome and Firefox return a date for 17 July 2019, Safari returns an invalid date.
It doesn't make sense to parse a string to get the values, then generate another string to be parsed by the built–in parser. Just give the first set of values directly to the Date constructor:
var inputToDate = new Date(todayYear, todayMonth - 1, todayDay);
which will work in every browser that ever supported ECMAScript.
Similarly:
var date = new Date();
var hours = date.getHours();
var minutes = date.getMinutes();
var ampm = hours >= 12 ? "pm" : "am";
hours = hours % 12;
hours = hours ? hours : 12; // the hour '0' should be '12'
minutes = minutes < 10 ? "0" + minutes : minutes;
var strTime = hours + ":" + minutes + " " + ampm;
var timeStart = new Date(todayDateText + " " + strTime);
appears to be a lengthy and brittle way to copy a date and set the seconds and milliseconds to zero. The following does exactly that in somewhat less code:
var date = new Date();
var timeStart = new Date(date);
timeStart.setMinutes(0,0);
use
var timeStart = new Date(todayDateText + " " + strTime)
Applying these changes to your code gives something like:
function parseMDY(s) {
var b = s.split(/\D/);
return new Date(b[2], b[0]-1, b[1]);
}
function formatDate(d) {
return d.toLocaleString(undefined, {
day: 'numeric',
month: 'short',
year: 'numeric'
});
}
// Call function with values
function checkform(dep_date, cut_offtime, dep_time) {
// Helper
function z(n) {
return (n<10?'0':'') + n;
}
// Convert dep_date to Date
var depD = parseMDY(dep_date);
// Get the departure time parts
var dtBits = dep_time.toLowerCase().match(/\d+|[a-z]+/gi);
var depHr = +dtBits[0] + (dtBits[2] == 'pm'? 12 : 0);
var depMin = +dtBits[1];
// Set the cutoff date and time
var cutD = new Date(depD);
cutD.setHours(depHr, depMin, 0, 0);
// Get current date and time
var now = new Date();
// Create cutoff string
var cutHr = cutD.getHours();
var cutAP = cutHr > 11? 'pm' : 'am';
cutHr = z(cutHr % 12 || 12);
cutMin = z(cutD.getMinutes());
var cutStr = cutHr + ':' + cutMin + ' ' + cutAP;
var cutDStr = formatDate(cutD);
// If before cutoff, OK
if (now < cutD) {
alert('Book before ' + cutStr + ' on ' + cutDStr);
return true;
// If after cutoff, not OK
} else {
alert('You should have booked before ' + cutStr + ' on ' + cutDStr);
return false;
}
}
// Samples
checkform('07/27/2019','1','6:00pm');
checkform('07/17/2019','1','11:00pm');
checkform('07/07/2019','1','6:00pm');
That refactors your code somewhat, but hopefully shows how to improve it and fix the parsing errors.

Calculate time difference and sum the difference using Javascript

i am trying to find the difference for end time and start time, followed by adding all the time difference
may i know how can i do so?
the code is as followed
function THcheck() {
var a, s, timeDiff, hr = 0;
var hdate, startTime, endTime, totalTime, timeDiff;
var output = "Date StartTime: EndTime: TimeDiff <br>";
var msg = "";
var DStime, DEtime;
var e = document.getElementsByTagName('input');
for (a = 0; e !== a; a++) {
if (e[a].type == "time" && e[a].name == "THStime[]") {
if (e[a].value && e[a].value !== "") {
startTime = e[a].value;
endTime = e[a + 1].value;
hdate = e[a - 1].value
alert(hdate + " " + startTime + " " + endTime);
timeDiff = endTime - startTime;
alert(timeDiff);
hr = parseInt(timeDiff.asHours());
alert(timeDiff);
totalTime += timeDiff;
alert(totalTime);
output += hdate + " " + startTime + " " + endTime + " " + timeDiff + "<br>";
if (hr >= 24) {
msg = "<br> Exceed 24 hrs! ";
}
}
}
}
alert(output + " Total time: " + totalTime + msg);
return true;
}
thanks in advance for your kind assistance and help on this!
I think you need to parse the hours first, converting from string to date and then convert the dates to milliseconds and use the milliseconds for the difference calculation. After this you convert the difference milliseconds into hours.
Here is some sample code which performs these steps:
const dateRegex = /(\d{2}):(\d{2})/;
function diffDatesInHours(d1Str, d2Str) {
const r1 = dateRegex.exec(d1Str);
const r2 = dateRegex.exec(d2Str);
if (!checkDate(r1)) {
console.log("First date format incorrect: " + d1Str);
return null;
}
if (!checkDate(r2)) {
console.log("Second date format incorrect: " + d2Str);
return null;
}
const d1 = createDateFrom(r1);
const d2 = createDateFrom(r2);
const diff = d1.getTime() - d2.getTime();
return Math.abs(diff) / (1000 * 60 * 60);
}
function checkDate(r) {
if (r === null) {
return null;
}
return r.length > 0;
}
function createDateFrom(r) {
let date = new Date();
date.setHours(r[1], r[2]);
return date;
}
console.log(diffDatesInHours("09:30", "21:00"));
console.log(diffDatesInHours("09:30", "21:"));

show time in HH:MM only in this javascript code [duplicate]

This question already has answers here:
Current time formatting with Javascript
(16 answers)
Closed 8 years ago.
The following JS shows the time in HH:MM:SS format while I need it to show HH:MM only
setInterval(function() {
var d = new Date();
var t = d.getTime();
var interval = 5*60*1000;
var last = t - t % interval;
var next = last + interval + 10*60000;
d.setTime(next);
var time = d.toLocaleTimeString();
$(".clock").html(time);
}, 1000);
Any idea on how to achieve that?
Fiddle: http://jsfiddle.net/7z9boag8/
There's getHours() and getMinuets() methods available.
example:
http://jsfiddle.net/0todu2y7/
jQuery(function($) {
setInterval(function() {
var d = new Date();
var t = d.getTime();
var interval = 5*60*1000;
var last = t - t % interval;
var nextt = last + interval + 5*60000;
d.setTime(nextt);
var hours = d.getHours();
var min = d.getMinutes();
$(".clock").html(hours+":"+min);
}, 1000);
});
i am sorry . i m not edit your code . i just give you another procedure
String.prototype.toHHMMSS = function () {
var sec_num = parseInt(this, 10); // don't forget the second param
var hours = Math.floor(sec_num / 3600);
var minutes = Math.floor((sec_num - (hours * 3600)) / 60);
var seconds = sec_num - (hours * 3600) - (minutes * 60);
if (hours < 10) {hours = "0"+hours;}
if (minutes < 10) {minutes = "0"+minutes;}
if (seconds < 10) {seconds = "0"+seconds;}
var time = hours+':'+minutes+':'+seconds;
return time;
}
Second Formula is
function checkTime(i) {
if (i < 10) {
i = "0" + i;
}
return i;
}
function yourTime() {
var today = new Date();
var h = today.getHours();
var m = today.getMinutes();
var s = today.getSeconds();
// add a zero in front of numbers<10
m = checkTime(m);
s = checkTime(s);
document.getElementById('time').innerHTML = h + ":" + m + ":" + s;
t = setTimeout(function () {
startTime()
}, 500);
}
yourTime();
Try this:
var time = d.toLocaleTimeString().match(/(\d+:\d+):\d+( \w{2})*/);
var time = time[1] + (time[2] ? time[2] : "");
setInterval(function() {
var d = new Date();
var t = d.getTime();
var interval = 5*60*1000;
var last = t - t % interval;
var next = last + interval + 10*60000;
d.setTime(next);
var time = d.toLocaleTimeString().split(':')
time.pop()
time.join(':')
$(".clock").html(time);
}, 60000);
I don't think that u shuold run tins function every second. U may do it once in minute.

How to keep updating datetime every minute in Javascript?

I am using following code to display date on my webpage. I need to update it every minute. How to do that?
var d=new Date();
var n=d.toString();
document.write(n);
Currently its static, means when the page load, datetime of that moment is displayed. I have to update time every minutes without refreshing the page.
Try with setInterval(): http://jsfiddle.net/4vQ8C/
var nIntervId; //<----make a global var in you want to stop the timer
//-----with clearInterval(nIntervId);
function updateTime() {
nIntervId = setInterval(flashTime, 1000*60); //<---prints the time
} //----after every minute
function flashTime() {
var now = new Date();
var h = now.getHours();
var m = now.getMinutes();
var s = now.getSeconds();
var time = h + ' : ' + m + ' : ' + s;
$('#my_box1').html(time); //<----updates the time in the $('#my_box1') [needs jQuery]
}
$(function() {
updateTime();
});
You can use document.getElementById("my_box1").innerHTML=time; instead of $('#my_box1')
from MDN:
About setInterval : --->Calls a function or executes a code snippet repeatedly, with a fixed time delay between each call to that function.
About setTimeout : ----> Calls a function or executes a code snippet after specified delay.
Here is how you can print date time every second
function displayDate()
{
var n=BuildDateString();
document.write(n);
window.setTimeout("displayDate();", 1000); // to print it every minute take 1000*60
}
function BuildDateString()
{
var today = new Date()
var year = today.getYear()
if (year < 2000)
year = "19" + year
var _day = today.getDate()
if (_day < 10)
_day = "0" + _day
var _month = today.getMonth() + 1
if (_month < 10)
_month = "0" + _month
var hours = today.getHours()
var minutes = today.getMinutes()
var seconds = today.getSeconds()
var dn = "AM"
if (hours > 12)
{
dn = "PM"
hours = hours - 12
}
if (hours == 0)
hours = 12
if (minutes < 10)
minutes = "0" + minutes
if (seconds < 10)
seconds = "0" + seconds
var DateString = _month+"/"+_day+"/"+year+" "+hours+":"+minutes+":"+seconds+" "+dn
return DateString;
}
I am using following approach:
var myVar=setInterval(function(){myDateTimer()},60000);
function makeArray()
{
for (i = 0; i<makeArray.arguments.length; i++)
this[i + 1] = makeArray.arguments[i];
}
function myDateTimer()
{
var months = new makeArray('January','February','March','April','May',
'June','July','August','September','October','November','December');
var days = ['Sunday','Monday','Tuesday','Wednesday','Thursday','Friday','Saturday'];
var date = new Date();
var day = date.getDate();
var month = date.getMonth() + 1;
var yy = date.getYear();
var year = (yy < 1000) ? yy + 1900 : yy;
var hours = date.getHours();
var minutes = date.getMinutes();
var finaldate = days[ date.getDay() ] + ", " + months[month] + " " + day + ", " + year + " " + hours +" : " + minutes;
document.getElementById("showDateTime").innerHTML=finaldate;
}
just do this
$(function(){
setInterval(function(){
var d=new Date();
var n=d.toString();
$('#test').html(n);
},1000);
});
demo http://runjs.cn/code/txlexzuc

how to create a javascript countdown which on refreshing continues counting

I try it with javascript and jquery but no idea how to do that. i wont to let the timer not begins on refreshing counting again. It´s same as an auction when he counting down 3,2 and on refreshing he don´t begins again it should continue count down where it last ended. And on other products it must count from 3 again. Have anyboy an idea?
Edit: because some users missunderstood what i am searching for.
my issue is that i don´t know how to save the time when someone refresh the page to continue to count it down. if someone refresh the site at 21sec and he or she have 30 secs to make there choice. and after refreshing the site, the counter will count at 21sec down and not started again by 30sec again.
no ajax.
When possible hardcoded.
And if not possible then the cookie variant.
You can set a name to your window on load of the page. Before setting the name check whether this window already has a name.
if it doesn't have a name, set a name to the window and start counting at 0 and save the count value in a cookie each time it increment.
if it does have a name(that means page is reloaded), read the count value from the cookie and do the increment and save to cookie.
EDIT: Example, Call initCount() function on body load. Use decrementAndSave function to decrement the value of the count and save it to cookie.
var count = 3;// 3 -> 2 -> 1
function getCookie(c_name) {
var i, x, y, ARRcookies = document.cookie.split(";");
for (i = 0; i < ARRcookies.length; i++) {
x = ARRcookies[i].substr(0, ARRcookies[i].indexOf("="));
y = ARRcookies[i].substr(ARRcookies[i].indexOf("=") + 1);
x = x.replace(/^\s+|\s+$/g, "");
if (x == c_name) {
return unescape(y);
}
}
}
function setCookie(c_name, value, exdays) {
var exdate = new Date();
exdate.setDate(exdate.getDate() + exdays);
var c_value = escape(value) + ((exdays == null) ? "" : "; expires=" + exdate.toUTCString());
document.cookie = c_name + "=" + c_value;
}
function initCount() {
if (window.name) {
count = getCookie("count_" + window.name);// to keep separate count cookies for each window
} else {
window.name = "w_" + (new Date().getTime());
count = 3;
setCookie("count_" + window.name, count, null);
}
}
function decrementAndSave() {
count--;
// separate cookie for each window or tab
setCookie("count_" + window.name, count, null);
}
It's not Perfect but I designed this script to do a 30min countdown and then to change some text during the last few seconds. The only issue with it is that when it gets to 1:00 it starts at 30:60 and I haven't figured out how to fix that yet. This may not work perfectly for what your looking for but it might put you on the right path.
<script>
//add leading zeros
setInterval(function() {
function addZero(i) {
if (i < 10) {
i = "0" + i;
}
return i;
}
var x = document.getElementById("timer");
var d = new Date();
var s = (d.getSeconds());
var m = (d.getMinutes());
var a = addZero(30 - m);
var b = addZero(60 - m);
var c = (60 - s);
var z = "<span style='color:red;font-size:50px;'>" + "Break" + "</span>";
var v = "<span style='color:black;font-size:24px;'>" + "Break" + "</span>";
//Decide how much should be subtracted from the time
if (m > 30) {
y = b;
}
else if (m < 30) {
y = a;
}
//elements for changing text
if (y < 2 && c < 15) {
q = z;
}
else {
q = v;
}
var t = y + (":" + addZero(c) + " Till Station " + (q));
x.innerHTML = t;
}, 250);
</script>
<div align="center" id="timer" style='color:black;font-size:24px;' ></div>
If you have a countdown, then you must have some sort of end time defined. So instead of having a countdown and just subtracting 1 every second, try something like this:
var endTime = new Date(2011,11,13,0,0,0); // Midnight of December 13th 2011
var timer = setInterval(function() {
var now = new Date();
var timeleft = Math.max(0,Math.floor((endTime.getTime()-now.getTime())/1000));
var d, h, m, s;
s = timeleft % 60;
timeleft = Math.floor(timeleft/60);
m = timeleft % 60;
timeleft = Math.floor(timeleft/60);
h = timeleft % 24;
timeleft = Math.floor(timeleft/24);
d = timeleft;
document.getElementById('counter').innerHTML = "Time left: "+d+" days, "+h+" hours, "+m+" minutes, "+s+" seconds.";
if( timeleft == 0) clearInterval(timer);
},1000);
var interval = 90000; //90 secounds
function reset() {
localStorage.endTime = +new Date() + interval;
}
if (!localStorage.endTime) {
reset();
}
function millisToMinutesAndSeconds(millis) {
var minutes = Math.floor(millis / 60000);
var seconds = ((millis % 60000) / 1000).toFixed(0);
return minutes + ":" + (seconds < 10 ? "0" : "") + seconds;
}
setInterval(function () {
var remaining = localStorage.endTime - new Date();
if (remaining >= 0) {
document.getElementById("tooltip").innerText =
millisToMinutesAndSeconds(remaining);
} else {
reset();
}
}, 100);

Categories