Calculate time difference and sum the difference using Javascript - 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:"));

Related

JavaScript Settimeout bug

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);

Problem with subtracting dates in real time with use setinterval

In this script I use some functions and xDate library for create true format dates. I am trying to make a small script, that show the difference between two dates with a times in real time, but I do not see an error in the code that does not allow this to be done. Where is the error?
jQuery(window).on("load", function() {
function parseISOLocal(s) {
// Split string into its parts
var b = s.split(/\D/);
// Create and return a date object
return new Date(b[0], b[1] - 1, b[2], b[3], b[4], b[5]);
}
// Convert a millisecond value to days, hours, minutes and seconds
function formatDHMS(ms) {
// Helper to add 's' to a number if other than 1
function addS(n) {
return n == 1 ? '' : 's';
}
var d = ms / 8.64e7 | 0;
var h = (ms % 8.64e7) / 3.6e6 | 0;
var m = (ms % 3.6e6) / 6e4 | 0;
var s = (ms % 6e4) / 1e3 | 0;
dd = (d != 0) ? d + ' day' + addS(d) + ', ' : "";
hh = (h != 0) ? h + ' hours' + addS(h) + ', ' : "";
mm = (m != 0) ? m + ' minute' + addS(m) + ', ' : "";
ss = (s != 0) ? s + ' second' + addS(s) + ' ' : "";
return ((d + h + m + s) > 0) ? dd + hh + mm + ss : "Time is over";
}
Date.prototype.addDays = function(days) {
var date = new Date(this.valueOf());
date.setDate(date.getDate() + days);
return date;
}
var date = new Date("2020-05-01 12:24:23");
var d1 = new XDate(date.addDays(2));
future_time = d1.toString("yyyy-MM-dd HH:mm:ss");
var d = new XDate();
current_time = d.toString("yyyy-MM-dd HH:mm:ss");
var someDate = new Date();
someDate.setDate(someDate.getDate() + 15); //number of days to add, e.x. 15 days
var dateFormated = someDate.toISOString().substr(0, 10);
console.log(dateFormated);
function Repeat() {
setInterval(function() {
current_time = d.toString("yyyy-MM-dd HH:mm:ss");
$('#timeForSign').html(formatDHMS(parseISOLocal(future_time) - parseISOLocal(current_time)));
}, 100);
}
setTimeout(Repeat, 500);
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="http://www.outsourcer.info/xdate.js"></script>
<div id="timeForSign"></div>
The issue is because you only ever compare the d value within the interval, and that never changes. To fix this you simply need to change d with new Date(), or new XDate(), if you'd prefer to use that library:
current_time = new XDate().toString("yyyy-MM-dd HH:mm:ss");
In addition there's quite a few variables in your JS which aren't necessary and can be removed. Try this:
jQuery(window).on("load", function() {
let future_time = parseISOLocal(new XDate(new Date("2020-05-01 12:24:23").addDays(2)).toString("yyyy-MM-dd HH:mm:ss"));
function Repeat() {
setInterval(function() {
let current_time = new XDate().toString("yyyy-MM-dd HH:mm:ss");
$('#timeForSign').html(formatDHMS(future_time - parseISOLocal(current_time)));
}, 100);
}
setTimeout(Repeat, 500);
});
Date.prototype.addDays = function(days) {
var date = new Date(this.valueOf());
date.setDate(date.getDate() + days);
return date;
}
function parseISOLocal(s) {
var b = s.split(/\D/);
return new Date(b[0], b[1] - 1, b[2], b[3], b[4], b[5]);
}
function formatDHMS(ms) {
let addS = (n) => n == 1 ? '' : 's';
let d = ms / 8.64e7 | 0;
let h = (ms % 8.64e7) / 3.6e6 | 0;
let m = (ms % 3.6e6) / 6e4 | 0;
let s = (ms % 6e4) / 1e3 | 0;
let t = [
d + ' day' + addS(d),
h + ' hour' + addS(m),
m + ' minute' + addS(h),
s + ' second' + addS(s)
];
return ms > 0 ? t.join(', ') : "Time is over";
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/xdate#0.8.2/src/xdate.js"></script>
<div id="timeForSign"></div>

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.

Javascript leading zero

I'm trying to use getHours and getMinutes to use them on a later function. The problem is that I always want the final number to be 3 or 4 digit and 2 digit. What happens is when the minutes are 0-9 the result of 1:04 is 14. This is my code and it doesn't fix the problem.
$hours = (new Date).getHours(),
$mins = (new Date).getMinutes();
function addZero($hours) {
if ($hours < 10) {
$hours = "0" + $hours;
}
return $hours;
}
function addZero($mins) {
if ($mins < 10) {
$mins = "0" + $mins;
}
return $mins;
}
$nowTimeS = $hours + "" + $mins;
// Convert string with now time to int
$nowTimeInt = $nowTimeS;
Problem is that you have two functions with same name, but you never call that function:
$date = new Date();
$hours = $date.getHours(),
$mins = $date.getMinutes();
$nowTimeS = addZero($hours) + "" + addZero($mins);
// Convert string with now time to int
$nowTimeInt = $nowTimeS;
function addZero($time) {
if ($time < 10) {
$time = "0" + $time;
}
return $time;
}
You defined your function twice using the same name and never called it
Perhaps you are looking for this?
function pad(num) {
return ("0"+num).slice(-2);
}
var d = new Date(),
hours = d.getHours(),
mins = d.getMinutes(),
nowTimeS = pad(hours) + ":" + pad(mins);
console.log(nowTimeS)

Cumbersome time parsing in JavaScript

I need a function to convert time in text from a format with day-part letters to digits.
E.g. 4:15PM -> 16:15, 4:15AM -> 4:15AM. Currently I have the following solution
function formatTime(text){
var find = '([0-9]|0[0-9]|1[0-9]|2[0-3]):[0-5][0-9] (AM|PM)';
var reg = new RegExp(find, 'g');
pos = 0;
var result;
var formatedText = "";
while((result = reg.exec(text)) !== null) {
if(result[2] == "PM"){
var hours= parseInt(result[0], 10);
hours = hours + 12;
var hoursStr = hours.toString();
var newTime = hoursStr + result[0].substring(result[1].length,result[0].length - 3);
formatedText += newTime;
pos = reg.lastIndex;
} else {
formatedText += text.replace("AM","").substring(pos, reg.lastIndex);
pos = reg.lastIndex;
}
}
if(pos < text.length){
formatedText += text.substring(pos, text.length);
}
return formatedText;
}
console.log(formatTime("Some Text (11:00AM - 1:00PM)"));
I makes nicely cases like
console.log(formatTime("Some Text (11:00AM - 1:00PM)"));
But I strugle to make it process
console.log(formatTime("Some Text (11:00 AM - 1:00 PM)"));
This works for your examples.
I've added \\s? to the regex and made a minor change in the logic of cutting time (-2 instead of -3). Also I've moved variables definition to the beginning of the function to reflect hoisting in JavaScript.
function formatTime(text){
var find = '([0-9]|0[0-9]|1[0-9]|2[0-3]):[0-5][0-9]\\s?(AM|PM)';
var reg = new RegExp(find, 'g');
var pos = 0;
var formatedText = "";
var result, hours, hoursStr, newTime;
while ((result = reg.exec(text)) !== null) {
if (result[2] === "PM") {
hours= parseInt(result[0], 10);
hours = hours + 12;
hoursStr = hours.toString();
newTime = hoursStr + result[0].substring(result[1].length, result[0].length - 2);
formatedText += newTime;
} else {
formatedText += text.replace("AM","").substring(pos, reg.lastIndex);
}
pos = reg.lastIndex;
}
if (pos < text.length) {
formatedText += text.substring(pos, text.length);
}
return formatedText;
}
Here's an easier way to do this: Just use two functions. One to convert the hours, and another to match against PM times along with the replace() function.
Easy does it...
function convertTime12to24(time12h) {
const [time, modifier] = time12h.split(' ');
let [hours, minutes] = time.split(':');
if (hours === '12') {
hours = '00';
}
if (modifier === 'PM') {
hours = parseInt(hours, 10) + 12;
}
return hours + ':' + minutes;
}
function formatTime(i_string) {
console.log(i_string.replace(/([0-9]|0[0-9]|1[0-9]|2[0-3]):([0-5][0-9])(PM)/gi, function newDate(x) {
return convertTime12to24(x.replace("PM", " PM"))
}));
}
formatTime("The time is now 4:15PM");
formatTime("The time is now 12:15PM");
formatTime("The time is now 4:00AM");
formatTime("The time is now 12:00AM");
formatTime("The time is now 11:00PM");

Categories