I'm basically trying to get the hours, minutes, and seconds of a date in javascript to read like this: '123456'. I am doing this with the following code:
var date;
date = new Date();
var time = date.getUTCHours() + date.getUTCMinutes() + date.getUTCSeconds();
Only problem is when I add them together, I keep getting the sum, not a nice line of 6 numbers like I want.
Any Suggestions?
var time = '' + date.getUTCHours() + date.getUTCMinutes() + date.getUTCSeconds();
edit:
To account for zero-padding you can do something like:
function format(x){
if (x < 10) return '0' + x;
return x;
}
var date;
date = new Date();
var time = '' + format(date.getUTCHours()) + format(date.getUTCMinutes()) + format(date.getUTCSeconds());
Convert the numerical value to a string:
var date;
date = new Date();
var time = date.getUTCHours().toString() + date.getUTCMinutes().toString() + date.getUTCSeconds().toString();
If you want it to always be 6 characters long, you need to pad the values if they are < 10. For example:
var hours = date.getUTCHours();
if (hours < 10)
hours = '0' + hours.toString();
else hours = hours.toString();
var mins = date.getUTCMinutes();
if (mins < 10)
mins = '0' + mins.toString();
else mins = mins.toString();
var secs = date.getUTCSeconds();
if (secs < 10)
secs = '0' + secs.toString();
else secs = secs.toString();
var time = hours + mins + secs;
That's happening because those functions return an Integer type. If you want to add the digits themself togheter, try converting every variable to string using toString()
Related
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)).
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.
I'm currently using this function to calculate 2 fields and the results are good but sometimes missing a zero. sample
10:20 + 10:30 current output 0.10
10:20 + 10:30 I want the output to be 00.10
$(function () {
function calculate() {
time1 = $("#start").val().split(':'),
time2 = $("#end").val().split(':');
hours1 = parseInt(time1[0], 10),
hours2 = parseInt(time2[0], 10),
mins1 = parseInt(time1[1], 10),
mins2 = parseInt(time2[1], 10);
hours = hours2 - hours1,
mins = 0;
if(hours < 0) hours = 24 + hours;
if(mins2 >= mins1) {
mins = mins2 - mins1;
} else {
mins = (mins2 + 60) - mins1;
}
// the result
$("#hours").val(hours + ':' + mins);
}
});
also when there is an invalid character I keep getting a nan message is possible to change this to 00 instead?
Instead of dealing with the strings and each value independently, you can use the javascript Date object to calculate the difference...
function calculate() {
// Get time values and convert them to javascript Date objects.
var time1 = new Date('01/01/2017 ' + $('#start').val());
var time2 = new Date('01/01/2017 ' + $('#end').val());
// Get the time difference in minutes. If is negative, add 24 hours.
var hourDiff = (time2 - time1) / 60000;
hourDiff = (hourDiff < 0) ? hourDiff+1440 : hourDiff;
// Calculate hours and minutes.
var hours = Math.floor(hourDiff/60);
var minutes = Math.floor(hourDiff%60);
// Set the result adding '0' to the left if needed
$("#hours").val((hours<10 ? '0'+hours : hours) + ':' + (minutes<10 ? '0'+minutes : minutes));
}
Or even better, you can make the function independent of the DOM elements, so you can reuse it...
function calculate(startTime,endTime) {
// Get time values and convert them to javascript Date objects.
var time1 = new Date('01/01/2017 ' + startTime);
var time2 = new Date('01/01/2017 ' + endTime);
// Get the time difference in minutes. If is negative, add 24 hours.
var hourDiff = (time2 - time1) / 60000;
hourDiff = (hourDiff < 0) ? hourDiff+1440 : hourDiff;
// Calculate hours and minutes.
var hours = Math.floor(hourDiff/60);
var minutes = Math.floor(hourDiff%60);
// Return the response, adding '0' to the left of each field if needed.
return (hours<10 ? '0'+hours : hours) + ':' + (minutes<10 ? '0'+minutes : minutes);
}
// Now you can use the function.
$("#hours").val(calculate($('#start').val(),$('#end').val()));
Add a function
function checkTime(i) {
if (i < 10) {i = "0" + i}; // add zero in front of numbers < 10
return i;
}
and call this function before displaying result
I propose you that :
$(".calculator").on("change",function(){
var isNegative = false;
var hours = "00:00";
var inputStart = $("#start").val();
var inputEnd = $("#end").val();
if(inputStart!="" && inputEnd != ""){
// calculate only if the 2 fields have inputs
// convert to seconds (more convenient)
var seconds1 = stringToSeconds(inputStart);
var seconds2 = stringToSeconds(inputEnd);
var secondsDiff = seconds2 - seconds1;
var milliDiffs = secondsDiff * 1000;
if(milliDiffs < 0){
milliDiffs = milliDiffs *-1;
isNegative = true;
}
// Convert the difference to date
var diff = new Date(milliDiffs);
// convert the date to string
hours = diff.toUTCString();
// extract the time information in the string 00:00:00
var regex = new RegExp(/[0-9]{2}:[0-9]{2}:[0-9]{2}/);
var arr = hours.match(regex);
hours = arr[0];
// Take only hours and minutes and leave the seconds
arr = hours.split(":");
hours=arr[0]+":"+arr[1];
// put minus in front if negative
if(isNegative){
hours = "-"+hours;
}
// Show the result
$("#hours").val(hours);
// Put back the inputs times in case there were somehow wrong
// (it's the same process)
var date1 = new Date(seconds1*1000);
var str1 = date1.toUTCString();
arr = str1.match(regex);
hours = arr[0];
arr = hours.split(":");
hours=arr[0]+":"+arr[1];
$("#start").val(hours);
// idem for time 2
var date2 = new Date(seconds2*1000);
var str2 = date2.toUTCString();
arr = str2.match(regex);
hours = arr[0];
arr = hours.split(":");
hours=arr[0]+":"+arr[1];
$("#end").val(hours);
}
});
function timeElementToString(timeElement){
var output = timeElement.toString();
if(timeElement < 10 && timeElement >=0)
output = "0"+output;
else if(timeElement < 0 && timeElement >=-10)
output = "-0"+Math.abs(output);
return output;
}
function stringToSeconds(input){
var hours = 0;
var arr=input.split(":");
if(arr.length==2){
hours=parseInt(arr[0]);
minutes=parseInt(arr[1]);
if(isNaN(hours)){
hours = 0;
}
if(isNaN(minutes)){
minutes = 0;
}
}
return hours*3600+60*minutes;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form>
<label for="start">Start</label><input type="text" id="start" class="calculator"></input><br />
<label for="end">End</label><input type="text" id="end" class="calculator"></input><br />
<label for="hours">Hours</label><input type="text" id="hours" readonly="readonly"></input>
</form>
This question already has answers here:
How do I get the difference between two Dates in JavaScript?
(18 answers)
Closed 7 years ago.
I'm trying to subtract two times from each other and for the most part works but in some scenarios it's giving the wrong output.
Here's my code so far:
//postDateTime looks like 2015-04-23T22:23:32.902Z
//Split the date and time
var postDateTime2 = postDateTime.split("T");
//remove the Z from the post time stamp
postDateTime2[1] = postDateTime2[1].replace('Z','');
//split the post date/time into sperate variables
var postDate = postDateTime2[0]; // date
var postTime = postDateTime2[1]; // time
//split up the post time into hours, minutes, seconds
var postTimeSplit = postTime.split(":");
var postTimeHour = postTimeSplit[0];
var postTimeMinutes = postTimeSplit[1];
var postTimeSeconds = postTimeSplit[2];
//split the date to have year, month, date separate
var postDateSplit = postDate.split("-");
//split the post date to year, month, date
var postYear = postDateSplit[0]; //year
var postMonth = postDateSplit[1]; //month
var postDate2 = postDateSplit[2]; //date
//get the current hour, minutes, seconds in UTC time.
var hours = now.getUTCHours();
var minutes2 = now.getUTCMinutes();
var seconds2 = now.getUTCSeconds();
//get the difference in years between post time and response time
var responseYear = Math.abs(now.getUTCFullYear() - postYear);
//get the difference in months between post time and response time
var responseMonth = Math.abs(mm - postMonth);
//get the difference in days between post time and response time
var responseDate = Math.abs(now.getUTCDate() - postDate2);
//get the difference in hours between post time and response time
var responseHour = Math.abs(now.getUTCHours() - postTimeHour);
//get the difference in minutes between post time and response time
var responseMinutes = Math.abs(now.getUTCMinutes() - postTimeMinutes);
//get the difference in seconds between post time and response time
var responseSeconds = Math.abs(now.getUTCSeconds() - postTimeSeconds);
Math.round(responseSeconds); // round the seconds to up to 2 decimal (doesn't work as expected)
So like I said, it works but if the time difference is more than one hour, it's starts giving weird outputs. For example if the real time difference has been only 38 minutes and the current time is an hour ahead, it will count it as 1 hours and 22 minutes.
Any suggestions how I can do this better?
So after some more research and thanks to Jasen, it was easier to convert my current time to a RFC 3339 time stamp and then find the difference that way in milliseconds and convert it back to a date. I also did some additional formatting for readability. Here's my final code:
//current time in RFC 3339 timestamp
function ISODateString(d){
function pad(n){return n<10 ? '0'+n : n}
return d.getUTCFullYear()+'-'
+ pad(d.getUTCMonth()+1)+'-'
+ pad(d.getUTCDate())+'T'
+ pad(d.getUTCHours())+':'
+ pad(d.getUTCMinutes())+':'
+ pad(d.getUTCSeconds())+'Z'
}
var d = new Date();
var currentTime = ISODateString(d);
//assign vars for current hour, minutes, seconds in UTC time.
var hours = d.getUTCHours();
var minutes = d.getUTCMinutes();
var seconds = d.getUTCSeconds();
//parse both time stamps into dates
var finalCurrentTime = Date.parse(currentTime);
var finalPostDateTime = Date.parse(postDateTime);
//find the difference between the original post date/time and the current date/time (in milliseconds)
var responseTimeFinal = Math.abs(finalCurrentTime - finalPostDateTime);
function dhm(ms){
var days2 = Math.floor(ms / (24*60*60*1000));
var daysms=ms % (24*60*60*1000);
var hours2 = Math.floor((daysms)/(60*60*1000));
var hoursms=ms % (60*60*1000);
var minutes2 = Math.floor((hoursms)/(60*1000));
var minutesms=ms % (60*1000);
var sec = Math.floor((minutesms)/(1000));
days2 = (days2 < 10) ? "0" + days2 : days2;
hours2 = (hours2 < 10) ? "0" + hours2 : hours2;
minutes2 = (minutes2 < 10) ? "0" + minutes2 : minutes2;
sec = (sec < 10) ? "0" + sec : sec;
//format day
if (days2 === "00"){
days2 = "";
} else if (days2 === "01"){
days2 = days2 + " day, ";
}
else if (days2 > "01"){
days2 = days2 + " days, ";
}
//format hours
if (hours2 === "00"){
hours2 = "";
}
else if (hours2 === "01"){
hours2 = hours2 + " hour, ";
}
else if (hours2 > "01"){
hours2 = hours2 + " hours, ";
}
//format minutes
if (minutes2 === "01"){
minutes2 = minutes2 + " minute, ";
}
else if (minutes2 > "01"){
minutes2 = minutes2 + " minutes, ";
}
//format seconds
if (sec === "01"){
sec = sec + " second";
}
else if (sec > "01"){
sec = sec + " seconds";
}
return days2+""+hours2+""+minutes2+""+sec;
}
//pass the milliseconds from responseTimeFinal into the dhm function to convert it back to a date
var timeDifference = dhm(responseTimeFinal);
console.log(timeDifference); // our final result that works!
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/