Leading zero when subtracting one time from another javascript - 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;

Related

How can I do sum two time values in javascript

I've been trying to implement the function that sums two values as hours.
"Example: 01:30 + 00:30 = 02:00"
So I have this function below that works only if the sum of the two values is equal to a round number such as the example above. But the problem is when the values are say 01:45 + 00:20 it gives me 33:05 instead of 02:05.
I've tried several combinations but nothing has worked so far.
function sumOFHoursWorked(){
var time1 = "00:45";
var time2 = "01:20";
var hour=0;
var minute=0;
var second=0;
var splitTime1= time1.split(':');
var splitTime2= time2.split(':');
hour = parseInt(splitTime1[0])+parseInt(splitTime2[0]);
minute = parseInt(splitTime1[1])+parseInt(splitTime2[1]);
hour = hour + minute/60;
minute = minute%60;
second = parseInt(splitTime1[2])+parseInt(splitTime2[2]);
minute = minute + second/60;
second = second%60;
var REalhourstime = ('0' + hour).slice(-2)+':'+('0' + minute).slice(-2);
alert(REalhourstime);
document.getElementById('realhorasTB').innerHTML = REalhourstime;
}
It actually depends on how your time will be, i mean it will be in mm:ss formet or hh:mm:ss or maybe hh:mm:ss:msms but for just simple second and minutes you can do something like this
function sumOFHoursWorked(){
var time1 = "00:45".split(':');
var time2 = "01:20".split(':');
let secondSum = Number(time1[1]) + Number(time2[1]);
let minSum = Number(time1[0]) + Number(time2[0]);
if(secondSum > 59){
secondSum = Math.abs(60 - secondSum);
minSum += 1;
}
if(secondSum < 10){
secondSum = `0${secondSum}`;
}
if(minSum < 10){
minSum = `0${minSum}`;
}
return `${minSum}:${secondSum}`;
}
console.log(sumOFHoursWorked());
I would convert it to minutes and subtract and then calculate hours and minutes.
function totalMinutes (time) {
var parts = time.split(":")
return +parts[0] * 60 + +parts[1]
}
function timeDiff (time1, time2) {
var mins1 = totalMinutes(time1)
var mins2 = totalMinutes(time2)
var diff = mins2 - mins1
var hours = '0' + (Math.floor(diff/60))
var minutes = '0' + (diff - hours * 60)
return (hours.slice(-2) + ':' + minutes.slice(-2))
}
console.log(timeDiff("00:45", "01:20"))
It will fail for times that go over midnight, a simple less than check can fix that.
function totalMinutes (time) {
var parts = time.split(":")
return +parts[0] * 60 + +parts[1]
}
function timeDiff (time1, time2) {
var mins1 = totalMinutes(time1)
var mins2 = totalMinutes(time2)
if (mins2 < mins1) {
mins2 += 1440
}
var diff = mins2 - mins1
var hours = '0' + (Math.floor(diff/60))
var minutes = '0' + (diff - hours * 60)
return (hours.slice(-2) + ':' + minutes.slice(-2))
}
console.log(timeDiff("23:45", "00:45"))
First of all, the time1 and time2 strings are missing the seconds at the end. For example, var time1 = "00:45:00". Otherwise, your calculation will have some NaN values.
The main issue is that hour is a floating point number (~ 2.083333333333333), so ('0' + hour) is '02.083333333333333'.
You could use something like this instead: ('0' + Math.floor(hour)).

CALCULATING TIME in 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;
}

Dateformat in javascript

I would like to get the date difference:
var dateString='2015-04-07T10:46:25Z';
var dt = new Date(value);
var now = new Date();
var _MS_PER_DAY = 1000 * 60 * 60 * 24;
var utc1 = Date.UTC(dt.getFullYear(), dt.getMonth(), dt.getDate());
var utc2 = Date.UTC(now.getFullYear(), now.getMonth(), now.getDate());
var days=Math.floor((utc2 - utc1) / _MS_PER_DAY);//this is 415
The result must be in this format: 415d, 03:06:33
What would be the best way to do that? I get date, but time is missing.
Try this
var datetime = new Date("2015-04-07T10:46:25Z");
var now = new Date();
if (datetime < now) {
var diffTime = now - datetime;
}else{
var diffTime = datetime - now;
}
var days = Math.floor(diffTime / 1000 / 60 / (60 * 24));
var dateDiff = new Date( diffTime );
var hour = dateDiff .getHours().toString().length == 1 ? '0' + dateDiff .getHours() : dateDiff .getHours();
var minute = dateDiff.getMinutes().toString().length == 1 ? '0' + dateDiff.getMinutes() : dateDiff.getMinutes();
var seconds = dateDiff.getSeconds().toString().length == 1 ? '0' + dateDiff.getSeconds() : dateDiff.getSeconds();
console.log(days + "d "+ hour + ":" + minute + ":" + seconds);
you need to use Modulus
var dt = new Date('2015-04-07T10:46:25Z');
var now = new Date();
var milSecondMil = 1000;
var secondMil = milSecondMil * 60;
var hourMil = secondMil * 60;
var dayMil = hourMil * 24;
var diff = now - dt;
var days = Math.floor(diff / dayMil);
var daysRemainder = diff % dayMil;
var hours = Math.floor(daysRemainder / hourMil);
var hoursRemainder = daysRemainder % hourMil;
var seconds = Math.floor(hoursRemainder / secondMil);
var secondsRemainder = hoursRemainder % secondMil;
var milSeconds = Math.floor(secondsRemainder / milSecondMil);
console.log(days + ' days - ' + hours + ' hours - ' + seconds + ' seconds - ' + milSeconds + ' mil');
I have done this way:
var dt = new Date(value);
var now = new Date();
var date1_ms = dt.getTime();
var date2_ms = now.getTime();
var diff=(date2_ms - date1_ms) / 1000;
var tm = new Date(null, null, null, null, null, Math.floor(diff % 86400)).toTimeString().split(" ")[0];
return Math.round(diff / (60 * 60 * 24)) + 'd, ' + tm;

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.

getting trouble in calculating time difference

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.

Categories