简体   繁体   中英

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); 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM