CALCULATING TIME in javascript - javascript

I am using this formula to calculate time between 2 different fields but result is in whole numbers and I need hours/minutes
time after dateFromString is example
var date1 = dateFromString(06: 00: 00);
var date2 = dateFromString(17: 30: 00);
var hours = Math.abs(date1 - date2) / 36e5;
return hours;
function dateFromString(isoDateString) {
var parts = isoDateString.match(/\d+/g);
var isoTime = Date.UTC(parts[0], parts[1] - 1, parts[2], parts[3], parts[4], parts[5]);
var isoDate = new Date(isoTime);
return isoDate;
}

Your code has some syntax errors, but try this, it should give you the time difference in an hours:minutes format:
var startTime = '06:00:00';
var endTime = '17:30:00';
var timeStart = new Date("01/01/2007 " + startTime);
var timeEnd = new Date("01/01/2007 " + endTime);
var minutesDiff = diff_minutes(timeStart, timeEnd);
var hoursAndMinsDiff = convertMinsToHrsMins(minutesDiff);
console.log(hoursAndMinsDiff)
function diff_minutes(dt2, dt1) {
var diff = (dt2.getTime() - dt1.getTime()) / 1000;
diff /= 60;
return Math.abs(Math.round(diff));
}
function convertMinsToHrsMins(mins) {
let h = Math.floor(mins / 60);
let m = mins % 60;
h = h < 10 ? '0' + h : h;
m = m < 10 ? '0' + m : m;
return `${h}:${m}`;
}
Is that what you're looking for?

Use division to get the hours, and then get the minutes using the remainder operation.
Also, dateFromString() expects the string to have both the date and time, not just a time, and it needs to be a quoted string.
var date1 = dateFromString("2018-12-01 06:00:00");
var date2 = dateFromString("2018-11-30 17:30:00");
var diffmin = Math.floor(Math.abs(date1 - date2) / 60000);
var hours = Math.floor(diffmin/60);
var minutes = diffmin % 60;
console.log(hours, minutes);
function dateFromString(isoDateString) {
var parts = isoDateString.match(/\d+/g);
var isoTime = Date.UTC(parts[0], parts[1] - 1, parts[2], parts[3], parts[4], parts[5]);
var isoDate = new Date(isoTime);
return isoDate;
}

Related

How to find difference between two DateTime Strings in Javascript

So I have two strings in javascript:
old_date = "2010-11-10 07:30:40";
new_date = "2010-11-15 08:03:22";
I want to find the difference between these two dates, but I am totally at a loss :(
I tried to do the following:
old_date_obj = new Date(Date.parse(old_date));
new_date_obj = new Date(Date.parse(new_date));
But it is giving me error. However that is only start of my woes...I need to show the difference as:
Difference is X Days, Y hours and Z minutes
Can JavaScript/jQuery gurus help me please? Much appreciated...
<script>
function Calculate() {
old_date = "2010-11-10 07:30:40";
new_date = "2010-11-15 08:03:22";
old_date_obj = new Date(Date.parse(old_date, "dd/mm/yyyy HH:mm:ss"));
new_date_obj = new Date(Date.parse(new_date, "dd/mm/yyyy HH:mm:ss"));
var utc1 = Date.UTC(new_date_obj.getFullYear(), new_date_obj.getMonth(), new_date_obj.getDate());
var utc2 = Date.UTC(old_date_obj.getFullYear(), old_date_obj.getMonth(), old_date_obj.getDate());
alert(Math.floor((utc2 - utc1) / (1000 * 60 * 60 * 24)));
}
</script>
simply add in you date and it will work for you.
"2010-11-10T07:30:40+01:00"
for more detail check this answer
Answer in detail
<script type="text/javascript">
// The number of milliseconds in one day, hour, and minute
var ONE_DAY = 1000 * 60 * 60 * 24;
var ONE_HOUR = 1000 * 60 * 60;
var ONE_MINUTE = 1000 * 60;
var old_date = "2010-11-10T07:30:40";
var new_date = "2010-11-15T08:03:22";
// Convert both dates to milliseconds
var old_date_obj = new Date(old_date).getTime();
var new_date_obj = new Date(new_date).getTime();
// Calculate the difference in milliseconds
var difference_ms = Math.abs(new_date_obj - old_date_obj)
// Convert back to days, hours, and minutes
var days = Math.round(difference_ms / ONE_DAY);
var hours = Math.round(difference_ms / ONE_HOUR) - (days * 24) - 1;
var minutes = Math.round(difference_ms / ONE_MINUTE) - (days * 24 * 60) - (hours * 60);
alert('Difference is ' + days + ' days, ' + hours + ' hours and ' + minutes + ' minutes.' );
</script>
<script type="text/javascript">
function getDates(strDate1, strDate2) {
/*Now strDate1 and strDate2 string. So we should convert them to javascript datetime value.*/
var tempDate1 = strDate1.split(/\-|\s/)
var date1 = new Date(tempDate1.slice(0,3).reverse().join('/')+' '+tempDate1[3]);
var tempDate2 = strDate2.split(/\-|\s/)
var date2 = new Date(tempDate2.slice(0,3).reverse().join('/')+' '+tempDate2[3]);
var obj1 = $.datepicker.parseDate('dd.mm.yy', $("#date1").val());
var obj2 = $.datepicker.parseDate('dd.mm.yy', $("#date2").val());
console.log(findDifferentDate(obj1, obj2));
}
function findDifferentDate(obj1, obj2){
var date1 = getFormattedDate(obj1);
var date2 = getFormattedDate(obj2);
var year = date1.getFullYear() - date2.getFullYear();
var day = date1.getDate() - date2.getDate();
var month = date1.getMonth() - date2.getMonth();
var seconds = date1.getSeconds() - date2.getSeconds();
var minutes = date1.getMinutes() - date2.getMinutes();
var hour = date1.getHours() - date2.getHours();
return 'Difference is' + day + 'Days' + month + 'Months' + year + 'Years' + seconds + 'Seconds' + minutes + 'Minutes' + hour + 'Hours';
}
function getFormattedDate(date) {
var year = date.getFullYear();
var month = (1 + date.getMonth()).toString();
month = month.length > 1 ? month : '0' + month;
var day = date.getDate().toString();
day = day.length > 1 ? day : '0' + day;
return day + '.' + month + '.' + year;
}
</script>
If you call getDates method with your dates and then u can see difference time in the console.
var old_date = "2010-11-15 07:30:40";
var new_date = "2010-11-15 08:03:22";
var old_date_obj = new Date(Date.parse(old_date));
var new_date_obj = new Date(Date.parse(new_date));
var diffMs = Math.abs(new_date_obj - old_date_obj);
var diffDays = Math.round(diffMs / 86400000); // days
var diffHrs = Math.round((diffMs % 86400000) / 3600000); // hours
var diffMins = Math.round(((diffMs % 86400000) % 3600000) / 60000); // minutes
https://jsfiddle.net/yps2wb58/1/

Check if current time is between two given times in JavaScript

I have two variables called 'startTime' and 'endTime'.
I need to know whether current time falls between startTime and EndTime. How would I do this using JavaScript only?
var startTime = '15:10:10';
var endTime = '22:30:00';
var currentDateTime = new Date();
//is current Time between startTime and endTime ???
UPDATE 1:
I was able to get this using following code. You can check out the code at: https://jsfiddle.net/sun21170/d3sdxwpb/1/
var dt = new Date();//current Date that gives us current Time also
var startTime = '03:30:20';
var endTime = '23:50:10';
var s = startTime.split(':');
var dt1 = new Date(dt.getFullYear(), dt.getMonth(), dt.getDate(),
parseInt(s[0]), parseInt(s[1]), parseInt(s[2]));
var e = endTime.split(':');
var dt2 = new Date(dt.getFullYear(), dt.getMonth(),
dt.getDate(),parseInt(e[0]), parseInt(e[1]), parseInt(e[2]));
alert( (dt >= dt1 && dt <= dt2) ? 'Current time is between startTime and endTime' :
'Current time is NOT between startTime and endTime');
alert ('dt = ' + dt + ', dt1 = ' + dt1 + ', dt2 =' + dt2)
var startTime = '15:10:10';
var endTime = '22:30:00';
currentDate = new Date()
startDate = new Date(currentDate.getTime());
startDate.setHours(startTime.split(":")[0]);
startDate.setMinutes(startTime.split(":")[1]);
startDate.setSeconds(startTime.split(":")[2]);
endDate = new Date(currentDate.getTime());
endDate.setHours(endTime.split(":")[0]);
endDate.setMinutes(endTime.split(":")[1]);
endDate.setSeconds(endTime.split(":")[2]);
valid = startDate < currentDate && endDate > currentDate
You can possibly do something like this if you can rely on your strings being in the correct format:
var setDateTime = function(date, str){
var sp = str.split(':');
date.setHours(parseInt(sp[0],10));
date.setMinutes(parseInt(sp[1],10));
date.setSeconds(parseInt(sp[2],10));
return date;
}
var current = new Date();
var c = current.getTime()
, start = setDateTime(new Date(current), '15:10:10')
, end = setDateTime(new Date(current), '22:30:00');
return (
c > start.getTime() &&
c < end.getTime());
I wanted to compare a time range in the day ... so I wrote this simple logic where the time is converted into minutes and then compared.
const marketOpen = 9 * 60 + 15 // minutes
const marketClosed = 15 * 60 + 30 // minutes
var now = new Date();
var currentTime = now.getHours() * 60 + now.getMinutes(); // Minutes since Midnight
if(currentTime > marketOpen && currentTime < marketClosed){ }
Note that I have not taken UTC minutes and hours since I want to use the local time, In my case it was IST time.
A different approach:
First, convert your currentDate
var totalSec = new Date().getTime() / 1000;
var hours = parseInt( totalSec / 3600 ) % 24;
var minutes = parseInt( totalSec / 60 ) % 60;
var seconds = totalSec % 60;
var numberToCompare = hours*10000+minutes*100+seconds;
cf Convert seconds to HH-MM-SS with JavaScript?
Then compare:
(numberToCompare < (endTime.split(':')[0]*10000+endTime.split(':')[1]*100+endTime.split(':')[2]*1)
or
(numberToCompare > (endTime.split(':')[0]*10000+endTime.split(':')[1]*100+endTime.split(':')[2]*1)
Just another way I have for matching periods in a day, precision is in minutes, but adding seconds is trivial.
function isValid(date, h1, m1, h2, m2) {
var h = date.getHours();
var m = date.getMinutes();
return (h1 < h || h1 == h && m1 <= m) && (h < h2 || h == h2 && m <= m2);
}
isValid(new Date(), 15, 10, 22, 30);

calculate time difference between two date in HH:MM:SS javascript

I have created one timer application in javascript.
Firstly it takes the current UTC date to init timer with some reference. here's the code
on_timer: function(e) {
var self = this;
if ($(e.target).hasClass("pt_timer_start")) {
var current_date = this.get_current_UTCDate();
this.project_timesheet_db.set_current_timer_activity({date: current_date});
this.start_interval();
this.initialize_timer();
this.$el.find(".pt_timer_start,.pt_timer_stop").toggleClass("o_hidden");
Now, Once timer is started and after some time span timer has some elapsed time with reference to above on_timer: function(e) function.
This function is
start_interval: function() {
var timer_activity = this.project_timesheet_db.get_current_timer_activity();
var self = this;
this.intervalTimer = setInterval(function(){
self.$el.find(".pt_duration").each(function() {
var el_hour = $(this).find("span.hours");
var el_minute = $(this).find("span.minutes");
var minute = parseInt(el_minute.text());
if(minute >= 60) {
el_hour.text(_.str.sprintf("%02d", parseInt(el_hour.text()) + 1));
minute = 0;
}
el_minute.text(_.str.sprintf("%02d", minute));
var el_second = $(this).find("span.seconds");
var seconds = parseInt(el_second.text()) + 1;
if(seconds > 60) {
el_minute.text(_.str.sprintf("%02d", parseInt(el_minute.text()) + 1));
seconds = 0;
}
el_second.text(_.str.sprintf("%02d", seconds));
});
}, 1000);
},
Now, considering el_hour, el_minute, el_seconds How to can i count time difference between init time and current timer value in HH:MM:SS manner.
thanks in advance for help
To convert H:M:S to seconds, you can use a simple function like:
// Convert H:M:S to seconds
// Seconds are optional (i.e. n:n is treated as h:s)
function hmsToSeconds(s) {
var b = s.split(':');
return b[0]*3600 + b[1]*60 + (+b[2] || 0);
}
Then to convert seconds back to HMS:
// Convert seconds to hh:mm:ss
// Allow for -ve time values
function secondsToHMS(secs) {
function z(n){return (n<10?'0':'') + n;}
var sign = secs < 0? '-':'';
secs = Math.abs(secs);
return sign + z(secs/3600 |0) + ':' + z((secs%3600) / 60 |0) + ':' + z(secs%60);
}
var a = '01:43:28';
var b = '12:22:46';
console.log(secondsToHMS(hmsToSeconds(a) - hmsToSeconds(b))); // -10:39:18
console.log(secondsToHMS(hmsToSeconds(b) - hmsToSeconds(a))); // 10:39:18
You may want to abbreviate the function names to say:
toHMS(toSec(a) - toSec(b)); // -10:39:18
Note that this doesn't cover where the time may cross a daylight saving boundary. For that you need fully qualified dates that include the year, month and day. Use the values to create date objects, find the difference, convert to seconds and use the secondsToHMS function.
Edit
The question title mentions dates, however the content only seems to mention strings of hours, minutes and seconds.
If you have Date objects, you can get the difference between them in milliseconds using:
var diffMilliseconds = date0 - date1;
and convert to seconds:
var diffSeconds = diffMilliseconds / 1000;
and present as HH:MM:SS using the secondsToHMS function above:
secondsToHMS((date0 - date1) / 1000);
e.g.
var d0 = new Date(2014,10,10,1,43,28);
var d1 = new Date(2014,10,10,12,22,46);
console.log( secondsToHMS((d0 - d1) / 1000)); // -10:39:18
I think there is a simpler solution.
function dateDiffToString(a, b){
// make checks to make sure a and b are not null
// and that they are date | integers types
diff = Math.abs(a - b);
ms = diff % 1000;
diff = (diff - ms) / 1000
ss = diff % 60;
diff = (diff - ss) / 60
mm = diff % 60;
diff = (diff - mm) / 60
hh = diff % 24;
days = (diff - hh) / 24
return days + ":" + hh+":"+mm+":"+ss+"."+ms;
}
var today = new Date()
var yest = new Date()
yest = yest.setDate(today.getDate()-1)
console.log(dateDiffToString(yest, today))
const dateDiffToString = (a, b) => {
let diff = Math.abs(a - b);
let ms = diff % 1000;
diff = (diff - ms) / 1000;
let s = diff % 60;
diff = (diff - s) / 60;
let m = diff % 60;
diff = (diff - m) / 60;
let h = diff;
let ss = s <= 9 && s >= 0 ? `0${s}` : s;
let mm = m <= 9 && m >= 0 ? `0${m}` : m;
let hh = h <= 9 && h >= 0 ? `0${h}` : h;
return hh + ':' + mm + ':' + ss;
};
This may be the simple answer
var d1 = new Date(2014,10,11,1,43,28);
var d2 = new Date(2014,10,11,2,53,58);
var date = new Date(d2-d1);
var hour = date.getUTCHours();
var min = date.getUTCMinutes();
var sec = date.getUTCSeconds();
var day = date.getUTCDate() - 1;
console.log(day + ":" + hour + ":" + min + ":" + sec)
More intuitive and easier to read.
function hmsToSeconds(t) {
const [hours, minutes, seconds] = t.split(':')
return Number(hours) * 60 * 60 + Number(minutes) * 60 + Number(seconds)
}
function secondsToHMS(secs) {
return new Date(secs * 1000).toISOString().substr(11, 8)
}
var startTime = '01:43:28';
var endTime = '12:22:46';
console.log(secondsToHMS(hmsToSeconds(endTime) - hmsToSeconds(startTime))); //10:39:18

how to convert the minutes into hours and minutes with subtracted time(subtracted time values)

I want to subtract the two different 24 hours time format.
I had tried with following :
var startingTimeValue = 04:40;
var endTimeValue = 00:55;
var hour = startingTimeValue.split(":");
var hour1 = endTimeValue.split(":");
var th = 1 * hour[0] - 1 * hour1[0];
var tm = 1 * hour[1] - 1 * hour1[1];
var time = th+":"+tm;
This code is working fine if second minutes is not greater than the first.but other case it will return minus values.
The above code sample values result :
time1 : 04:40
time2 : 00:55
The result should be : 03:45 (h:mi) format.
But right now I am getting 04:-5 with minus value.
I had tried with the link as : subtract minutes from calculated time javascript but this is not working with 00:00 format.
So how to calculate the result value and convert into hours and minutes?
I would try something like the following.
The way I see it, it is always better to break it down to a common unit and then do simple math.
function diffHours (h1, h2) {
/* Converts "hh:mm" format to a total in minutes */
function toMinutes (hh) {
hh = hh.split(':');
return (parseInt(hh[0], 10) * 60) + parseInt(hh[1], 10);
}
/* Converts total in minutes to "hh:mm" format */
function toText (m) {
var minutes = m % 60;
var hours = Math.floor(m / 60);
minutes = (minutes < 10 ? '0' : '') + minutes;
hours = (hours < 10 ? '0' : '') + hours;
return hours + ':' + minutes;
}
h1 = toMinutes(h1);
h2 = toMinutes(h2);
var diff = h2 - h1;
return toText(diff);
}
Try:
var time1 = Date.UTC(0,0,0,4,40,0);
var time2 = Date.UTC(0,0,0,0,55,0);
var subtractedValue = time1 - time2;
var timeResult = new Date(subtractedValue);
console.log(timeResult.getUTCHours() + ":" + timeResult.getUTCMinutes());
DEMO
This solution utilizes javascript built-in date. How it works:
var time1 = Date.UTC(0,0,0,4,40,0);
var time2 = Date.UTC(0,0,0,0,55,0);
time1, time2 is the number of miliseconds since 01/01/1970 00:00:00 UTC.
var subtractedValue = time1 - time2;
subtractedValue is the difference in miliseconds.
var timeResult = new Date(subtractedValue);
console.log(timeResult.getUTCHours() + ":" + timeResult.getUTCMinutes());
These lines reconstruct a date object to get hours and minutes.
This works better , A fiddle I just found
var difference = Math.abs(toSeconds(a) - toSeconds(b));
fiddle
This method may work for you:
function timeDiff(s,e){
var startTime = new Date("1/1/1900 " + s);
var endTime = new Date("1/1/1900 " + e);
var diff = startTime - endTime;
var result = new Date(diff);
var h = result.getUTCHours();
var m = result.getUTCMinutes();
return (h<=9 ? '0' + h : h) + ':' + (m <= 9 ? '0' + m : m);
}
var startingTimeValue = "04:40";
var endTimeValue = "00:55";
var formattedDifference = timeDiff(startingTimeValue,endTimeValue);
Demo: http://jsfiddle.net/zRVSg/

Leading zero when subtracting one time from another javascript

function setValue() {
var startTime = document.getElementById('ToilA');
var endTime = document.getElementById('EndHours'); startTime = startTime.value.split(":");
var startHour = parseInt(startTime[0], 10);
var startMinutes = parseInt(startTime[1], 10);
endTime = endTime.value.split(":");
var endHour = parseInt(endTime[0], 10);
var endMinutes = parseInt(endTime[1], 10);
//var hours, minutes;
var today = new Date();
var time1 = new Date(2000, 01, 01, startHour, startMinutes, 0);
var time2 = new Date(2000, 01, 01, endHour, endMinutes, 0); var milliSecs = (time2 - time1);
msSecs = (1000);
msMins = (msSecs * 60);
msHours = (msMins * 60);
numHours = Math.floor(milliSecs/msHours);
numMins = Math.floor((milliSecs - (numHours * msHours)) / msMins);
numSecs = Math.floor((milliSecs - (numHours * msHours) - (numMins * msMins))/ msSecs); numSecs = "0" + numSecs;
numMins = "0" + numMins;
DateCalc = (numHours + ":" + numMins);
document.getElementById('CalculateHours').value = DateCalc; }
I have one more issue with this code, there is a leading 0 when the minute part is over 10.
so it return something like 11:013 rather that 11:13, can this be fixed with math or will an if statement fix this? Like if number of items > 2, remove first item?
I was going to just do a PHP script to remove this when the form is submitted, but it doesn't look good.
Change numMins = "0" + numMins to
if (numMins < 10)
numMins = "0" + numMins;
if (numSecs < 10)
numSecs = "0" + numSecs;
if (numMins < 10)
numMins = "0" + numMins;

Categories