getting trouble in calculating time difference - javascript

this is my javascript code to calculate time difference:
var startTime = '11:30 am';
var EndTime = '1:30 pm';
var ed = EndTime.split(':');
var st = startTime.split(':');
var sub = parseInt(ed[0]) * 60 + parseInt(ed[1]);
var sub1 = parseInt(st[0]) * 60 + parseInt(st[1]);
i am getting outout:-600
i want difference in output as:2 hour.
can anybody figure out whats wrong with my code??

I would suggest
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);
return (hours < 9 ? "0" : "") + hours + ":" + (minutes < 9 ? "0" : "") + minutes;
}
Check this fiddle
http://jsfiddle.net/shubhambhave/D9M8a/

Please, use more your mind.
First, you're not even looking at the AM or PM.
If you are sure your times will look like this (and not timestamp or anything else), you can do this (I try to keep your logic here):
var startTime = '11:30 am';
var endTime = '1:30 pm';
var st = startTime.split(':');
var ed = endTime.split(':');
if ((st[1].split(' '))[1] == 'pm')
st[0] = parseInt(st[0]) + 12;
if ((ed[1].split(' '))[1] == 'pm')
ed[0] = parseInt(ed[0]) + 12;
st[1] = (st[1].split(' '))[0];
ed[1] = (ed[1].split(' '))[0];
var diff = ((ed[0] * 60 + ed[1] * 60) - (st[0] * 60 + st[1] * 60)) / 60;
In fact, you forgot to remove the 'am' part of the time.
You also forget to calculate it.
This code can be refactored, but i'm not gonna do all the job.

Related

Difference between two html time inputs

I try to calculate the difference between two HTML time input elements. At the moment that one of the times is changed, there has to be recalculated, unfortunately I can not do this for each other. Who can help me?
<input type="time" id="start" value="10:00" >
<input type="time" id="end" value="12:30" >
<input id="diff">
<script>
var start = document.getElementById("start").value;
var end = document.getElementById("end").value;
document.getElementById("start").onchange = function() {diff(start,end)};
document.getElementById("end").onchange = function() {diff(start,end)};
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);
return (hours < 9 ? "0" : "") + hours + ":" + (minutes < 9 ? "0" : "") + minutes;
}
document.getElementById("diff").value = diff(start, end);
</script>
This time difference code is amazing! So if all you need is for it to update itself, I copied and slightly remodeled your code for you. Again, your code is amazing :)
<input type="time" id="start" value="10:00" >
<input type="time" id="end" value="12:30" >
<input id="diff">
<script>
var start = document.getElementById("start").value;
var end = document.getElementById("end").value;
document.getElementById("start").onchange = function() {diff(start,end)};
document.getElementById("end").onchange = function() {diff(start,end)};
function diff(start, end) {
start = document.getElementById("start").value; //to update time value in each input bar
end = document.getElementById("end").value; //to update time value in each input bar
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);
return (hours < 9 ? "0" : "") + hours + ":" + (minutes < 9 ? "0" : "") + minutes;
}
setInterval(function(){document.getElementById("diff").value = diff(start, end);}, 1000); //to update time every second (1000 is 1 sec interval and function encasing original code you had down here is because setInterval only reads functions) You can change how fast the time updates by lowering the time interval
</script>
Is this what you want, if not, tell me, I'll be happy to help with this magnificent code :)
With your code, you get the value of start and end just one time..you have to get the value each time you want to calculate the difference
try to do
document.getElementById("start").onchange = function() {
var start = document.getElementById("start").value;
var end = document.getElementById("end").value;
diff(start,end)};
and the same thing for the other element.
//You can create a function like this that returns the difference between two times in hours it accepts as parameters string in format time "hh:mm";
function timeDiffInHours(time1, time2){
time1Arr = time1.split(":");
time1InMinutes = parseInt(time1Arr[0])*60+parseInt(time1Arr[1]);
time2Arr = time2.split(":");
time2InMinutes = parseInt(time2Arr[0])*60+parseInt(time2Arr[1]);
diff = time2InMinutes - time1InMinutes;
return Math.floor(100*diff/60)/100;
}
console.log(timeDiffInHours("08:30","18:30");
//Response : 10

How to get UTC timezone in javascript and adjust to PDT/PT

I have a countdown timer timer constructed but it's just using getTime(), i'm unsure how to adjust this so it is the correct timezone i want (PDT/PT)
var countdownTimer = setInterval(countdownTick, 1000);
function countdownTick() {
jQuery('ul.countdown').each(function() {
var date = jQuery(this).attr('data-date').split('-'); // Create date array from attribute
var time = jQuery(this).attr('data-time').split('-'); // Create time array from attribute
for (var i = 0; i < date.length; i++) {
date[i] = parseInt(date[i]);
}
for (var i = 0; i < time.length; i++) {
time[i] = parseInt(time[i]);
}
var today = new Date();
var theDate = new Date(date[0], (date[1] - 1), date[2], time[0], time[1]);
if (theDate.getTime() > today.getTime()) { // If the target date is in the future
countdownCalc(this, theDate, today); // Calculate how much time there is until the target date
}
});
}
function countdownCalc(obj, targetDate, currentDate) {
var oneDay = 1000 * 60 * 60 * 24;
var oneSecond = 1000;
var output = (targetDate.getTime() - currentDate.getTime());
var day = Math.floor(output / oneDay);
var hour = Math.floor((output - (day * oneDay)) / (1000 * 60 * 60));
var minute = Math.floor((output - (hour * (1000 * 60 * 60) + (day * oneDay))) / (1000 * 60));
var second = Math.floor((output - ((minute * 60000) + (hour * 1000 * 60 * 60) + (day * oneDay))) / 1000);
jQuery(obj).html('<li><span class="countdown-label">DAYS</span><span class="countdown-number">' + day + '</span></li><li><span class="countdown-label">HOURS</span><span class="countdown-number">' + hour + '</span></li><li><span class="countdown-label">MINUTES</span><span class="countdown-number">' + minute + '</span></li><li><span class="countdown-label">SECONDS</span><span class="countdown-number">' + second + '</span></li>');
}
https://jsfiddle.net/4nag4h5v/
Here is where plugins become useful, using moment-timezone.js
We are able to do something is simple as:
let time = Date.now();
moment(time).tz("YOURTIMEZONE").format('x') // get timestamp (in milliseconds
Without using an external library, the simplest way to do it is by using an offset between your local and target timezones:
let today = new Date(),
localOffset = -(today.getTimezoneOffset()/60),
targetOffset = -8,
netOffset = targetOffset - targetOffset;
const d = new Date(new Date().getTime() + netOffset * 3600 * 1000);

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/

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

Get Sum of Javascript Date function

I have code for get time difference form two time
var starthours = document.getElementById("time3").value;
var endhours = document.getElementById("time4").value;
start = starthours.split(".");
end = endhours.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);
document.getElementById("hourdiff").value = (hours < 9 ? "0" : "") + hours + "." + (minutes < 9 ? "0" : "") + minutes;
But now I have to add another time field for this results, I get that value using this code
var timetv = document.getElementById("timetv").value;
And I want to add this to above time difference how to do that, Please help me..
Start time = 10.30
End time = 12.30
Time TV = 01.15
Resualt = (End Time - Start time) + Time TV
And answer should be = 3.15
Try This,
var starthours = document.getElementById("time3").value;
var endhours = document.getElementById("time4").value;
var timetv = document.getElementById("timetv").value;
start = starthours.split(".");
end = endhours.split(".");
tvtime = timetv.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);
hours = hours + parseInt(tvtime[0]);
minutes = minutes + parseInt(tvtime[1]);
this one is for getting the value when you already have the dates parsed into Date object from your form.
http://jsfiddle.net/gLReS/
var time1 = new Date('2013/08/12 10:30');
var time2 = new Date('2013/08/12 12:30');
var time3 = new Date('2013/08/12 1:15');
var result = (time2.getTime() - time1.getTime()) + time3.getTime();
var resultTime = new Date(result);
alert(resultTime);
The other thing is however getting these objects, and this one depends on your date format.
I don't understand, what is your problem.
var d = new Date(
new Date(0, 0, 0, 12, 30) -
new Date(0, 0, 0, 10, 30) +
(+new Date(0, 0, 0, 1, 15)) // transform Date into timestamp
);
[d.getHours(), d.getMinutes()]; // [3, 15]
Also, I usually replace
(hours < 9 ? "0" : "") + hours
with
("0" + hours).slice(-2)

Categories