convert seconds to {H hr MM min} time format with javascript - javascript

How can I convert seconds to (H hr mm min) format by Javascript?
Example : 4 hr 30 min
I found other solutions here, but they didn't help me.

hours is
(total_seconds / 60) / 60
minutes is
(total_seconds / 60) % 60
seconds is
(total_seconds % 60) % 60
where / is integer division (division that discards the remainder) and % is the modulo function.

Use JavaScript's built-in Date function:
// Randomly selected number of seconds
var seconds = 23568;
// Pass it to the Date-constructor (year, month, day, hours, minutes, seconds)
var d = new Date(0, 0, 0, 0, 0, seconds);
// Get result as a "formatted" string, and show it.
var myString = d.getHours().toString() + ':' + d.getMinutes().toString() + ':' + d.getSeconds().toString();
alert(myString);

Below is the given code which will convert seconds into hh-mm-ss format:
var measuredTime = new Date(null);
measuredTime.setSeconds(4995); // specify value of SECONDS
var MHSTime = measuredTime.toISOString().substr(11, 8);
Source: Convert seconds to HH-MM-SS format in JavaScript

Related

How to convert hours:minutes using javascript

I am currently working on Jvascript datetime part in that getting NaN error while converting hours and minutes to seconds like strtotime in PHP so I want to know how to convert minutes and seconds like the way we do in strtotime in PHP.
var d = new Date();
var total = d.getHours() + ":" + d.getMinutes();
var ts = Date.parse(total);
document.write(ts);
In output getting error NaN
This is a sort of inane question, but here's the number of seconds in the hours and minutes of that number:
var d = new Date();
var total = (d.getHours() * 60 * 60) + (d.getMinutes() * 60);
document.write(total);
First of all, Date.parse() takes a string of a specific format (such as Jul 18, 2018). Second, it will not convert the date to seconds, but will return the number of milliseconds since January 1, 1970 00:00:00 GMT.
If you need to convert hh:mm to seconds, the correct approach is to multiply the value of getHours() by 3600 and multiply the value of getMinutes() by 60, then sum up the two values.
var d = new Date();
var timeinsecs = d.getHours() * 3600 + d.getMinutes() * 60;
document.write(timeinsecs);
While if you need to get the time in seconds from January 1, 1970 00:00:00 GMT till the current time, you will need to parse the current date then divide by 1000:
var d = new Date();
document.write(Date.parse(d) / 1000);
Just get hours and minutes, then sum them multiplying hours * 3600 and minutes * 60, like this
var d = new Date();
var total = d.getHours() * 3600 + d.getMinutes() * 60;
document.write(total)
If you want to follow your original approach of not doing the math by hand, you need to include a date before the time (any date should do, could be today if you wish) and convert ms to seconds (both of these for the reasons Wais Kamal pointed out) as follows.
var d = new Date();
var total = d.getHours() + ":" + d.getMinutes();
var someDate ='July 4, 1776';//works, but maybe safer to choose since 1990
total=someDate+', '+total;
var ts = Date.parse(total);
document.write((ts- Date.parse(someDate))/1000);

How to multiply time using javascript?

I have the following timespan coming from a model in MVC:
timeTaken = "00:01:00";
Then I have a multiplier
multiply = "3";
Result: 00:03:00
What would be the best way to calculate this time?
I don't know a great deal of libraries. I was thinking of splitting the seconds, minutes and hours, dividing each one into seconds, multiplying then putting it back together.
However, I have this kind of calculations for many sections, it just seems a little mundane. Can I just multiply the time in a better manner?
Thanks
I am combining the snippets I found in multiple pages. Conversion of hh:mm:ss to seconds, multiply 3x and then again convert to hh:mm:ss.
var hms = '00:01:00'; // your input string
var a = hms.split(':'); // split it at the colons
// minutes are worth 60 seconds. Hours are worth 60 minutes.
var seconds = (+a[0]) * 60 * 60 + (+a[1]) * 60 + (+a[2]);
var newSeconds= 3*seconds;
// multiply by 1000 because Date() requires miliseconds
var date = new Date(newSeconds * 1000);
var hh = date.getUTCHours();
var mm = date.getUTCMinutes();
var ss = date.getSeconds();
// If you were building a timestamp instead of a duration, you would uncomment the following line to get 12-hour (not 24) time
// if (hh > 12) {hh = hh % 12;}
// These lines ensure you have two-digits
if (hh < 10) {hh = "0"+hh;}
if (mm < 10) {mm = "0"+mm;}
if (ss < 10) {ss = "0"+ss;}
// This formats your string to HH:MM:SS
var t = hh+":"+mm+":"+ss;
document.write(t);
JSFiddle
First you can convert them to seconds as below
var hms = "00:01:00";
var a = hms.split(':'); // split it at the colons
// minutes are worth 60 seconds. Hours are worth 60 minutes.
var seconds = (+a[0]) * 60 * 60 + (+a[1]) * 60 + (+a[2]);
var newSeconds=seconds * 3;
var t = new Date();
t.setSeconds(newSeconds);
console.log(t);
DEMO
Update
To just obtain time do as below
var time=t.toTimeString().split(' ')[0]
DEMO
UPDATE
To obtain just hour from time you can do as follows
t.toTimeString().split(' ')[0].split(':')[0]
and to obtain hour in 12 hour format you can do as below:
var hour;
if(t.toTimeString().split(' ')[0].split(':')[0]>12)
hour=t.toTimeString().split(' ')[0].split(':')[0]-12;
else
hour=t.toTimeString().split(' ')[0].split(':')[0];
alert(hour);
UPDATED DEMO

Why Time difference gives me 2 different results

this code should give 0:40 minutes, however in one way gives me 0:20 minutes, and in the other way gives me 1:40 minutes.
var t1 = '12:05'.split(':'),
t2 = '12:45'.split(':');
var d1 = new Date(0,0,0,t1[0],t1[1]),
d2 = new Date(0,0,0,t2[0],t2[1]);
document.write(d1+'<BR>');
document.write(d2+'<BR>');
var d = new Date(d1-d2);
// should give 0:40 minutes
document.write(d.getHours() + ":" + d.getMinutes() + '<BR>');
// 0:20 minutes
var d = new Date(d2-d1);
document.write(d.getHours() + ":" + d.getMinutes() + '<BR>');
// 1:40 minutes
Any ideas?
You can write your own function to calculate two dates difference and show the result in HH:MM format.
Because Javascript returns two date difference in timestamp & if we use that timestamp to get JS date object it creates totally new date.
Here is the sample dateDiff function :
function dateDiff(){
var start = '12:05'.split(':'), // hardcoded value for sample
end = '12:45'.split(':'); // you can pass start and end value as parameter to dateDiff function.
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);
}
Subtracting two dates gives you the number of milliseconds between them. Passing this to new Date gives you a new date object that many milliseconds from epoch.
If you want the number of minutes between two dates, just do this:
(d1-d2)/(60*1000);

Hour to Minutes 00:00 to 00 javascript

I need to convert hours:minutes (00:00) to minutes 00 in Javascript.
I thought about doing it by using substr to get hour and minutes separately and then multiply the hours part by 60 and then add the minutes part.
Is there any other easy way to do this?
It's pretty easy with split:
var str = "04:17";
var parts = str.split(":");
var minutes = parseInt(parts[0], 10) * 60 + parseInt(parts[1], 10);
console.log(minutes); // 257 (four hours and seventeen minutes)
To split in hour and minute, you can use the split() function on the String object:
"12:05".split(':');
--> ["12", "05"]
Then you need to convert the Strings in the array to integers with parseInt:
var hours = parseInt("12", 10);
var minutes = parseInt("05", 10);
Then rest is simple calculation:
var total = hours * 60 + minutes;

String to date conversion not working correctly in Javascript

I need to get time difference in this format: "HH:MM:SS" using a Javascript.
I have tried this:
var diff = Date.parse( time2) - Date.parse( time1 );
var total_time = (diff / 1000 / 60 / 60) + ":" + (diff / 1000 / 60) + ":" + (diff / 1000);
and this:
var diff = new Date( time2) - new Date( time1 );
var total_time = (diff / 1000 / 60 / 60) + ":" + (diff / 1000 / 60) + ":" + (diff / 1000);
These are the values of time2 and time1:
time1: "2012-11-07 15:20:32.161"
time2: "2012-11-07 17:55:41.451"
And result I am getting in both cases is:
total_time= 0.5250819444444444:31.504916666666666:1890.295
Which you can see is not correct
I think you are getting wrong diff value because of the millisecond part in the date delimited by .. Its not being accepted correctly by the data parser.
Try using the date and time part excluding the milliseconds as below:
var diff = Date.parse(time2.split(".")[0]) - Date.parse( time1.split(".")[0]);
Also while you are getting wrong difference diff, your time computation is also wrong.
It should be:
var second = Math.floor(diff /1000);
//convert the seconds into minutes and remainder is updated seconds value
var minute = Math.floor(second /60);
second = second % 60;
//convert the minutes into hours and remainder is updated minutes value
var hour = Math.floor(minute/60);
minute = minute %60;
var total_time= hour+":" minute+":"+second;
You forgot to remove the number of milliseconds you already calculated from diff. Here is a very verbose example on how you do it in a propper way.
var time1 = "2012-11-07 15:20:32.161",
time2 = "2012-11-07 17:55:41.451",
SECOND = 1000,
MINUTE = SECOND* 60,
HOUR = MINUTE* 60;
var diff = new Date(time2) - new Date(time1);
var hours = Math.floor(diff / HOUR); // Calculate how many times a full hour fits into diff
diff = diff - (hours * HOUR); // Remove hours from difference, we already caluclated those
var minutes = Math.floor(diff / MINUTE); // Calculate how many times a full minute fits into diff
diff = diff - (minutes * MINUTE); // Remove minutes from difference
var seconds = Math.floor(diff / SECOND); // As before
diff = diff - (seconds * SECOND);
var rest = diff;
var total_time = hours + ":" + minutes + ":" + seconds + " " + rest ;
DEMO

Categories

Resources