开发者

Best way to convert 5PM to 17:00 (12hr to 24hr)

开发者 https://www.devze.com 2023-03-04 12:23 出处:网络
I would like to be able to convert simple one digit time strings into full timest开发者_高级运维amp that javascript can understand.

I would like to be able to convert simple one digit time strings into full timest开发者_高级运维amp that javascript can understand.

For Example:

'1PM' => 13:00
'5AM' => 05:00
'7:15PM' => 19:15
etc, etc

I want to create bullet proof time input field that will accept any time format thrown at it.


I don't know of a way of doing this with built in JavaScript stuff e.g. Date. You might have to roll your own e.g. parse the number using JavaScript string functions, then create a Date object and call setHours and setMinutes on it.


Depending on how bullet proof you want your code to be, you might want to try datejs which is 25.2 KB.


I came up with this as an approximation:

new Date (new Date().toDateString() + ' ' + '10:55 PM').toTimeString().split(' ')[0]

The problem here is that it won't work with the formats in your example. They need to be at least 1:00 PM (HH:MM and a space between the time and AM/PM)

0

精彩评论

暂无评论...
验证码 换一张
取 消