suresh64633 Posted September 22, 2009 Share Posted September 22, 2009 How can i convert my time string "10:00 PM" to "22:00:00"; Quote Link to comment https://forums.phpfreaks.com/topic/175104-converting-12-hours-format-to-24-hrs-format/ Share on other sites More sharing options...
Psycho Posted September 22, 2009 Share Posted September 22, 2009 <html> <head> <script type="text/javascript"> function convert12to24(timeStr) { var meridian = timeStr.substr(timeStr.length-2).toLowerCase();; var hours = timeStr.substr(0, timeStr.indexOf(':')); var minutes = timeStr.substring(timeStr.indexOf(':')+1, timeStr.indexOf(' ')); if (meridian=='pm') { if (hours!=12) { hours=hours*1+12; } else { hours = (minutes!='00') ? '0' : '24' ; } } return hours+':'+minutes; } //This function only for testing function changeTimeFormat() { var input = document.getElementById('input').value var output = convert12to24(input); document.getElementById('output').value = output; } </script> </head> <body> Input 12 hr format: <input type="text" name="input" value="10:30 PM"><br /> Output 24 hr format: <input type="text" name="output" value="" readonly> <button onclick="changeTimeFormat();">Change</button> </form> </body> </html> Quote Link to comment https://forums.phpfreaks.com/topic/175104-converting-12-hours-format-to-24-hrs-format/#findComment-923058 Share on other sites More sharing options...
suresh64633 Posted September 23, 2009 Author Share Posted September 23, 2009 thanks Quote Link to comment https://forums.phpfreaks.com/topic/175104-converting-12-hours-format-to-24-hrs-format/#findComment-923352 Share on other sites More sharing options...
Psycho Posted September 23, 2009 Share Posted September 23, 2009 Improved the function. - 00:00 should be used instead of 24:00 - added functionality to ensure hours is always two digits. function convert12to24(timeStr) { var meridian = timeStr.substr(timeStr.length-2).toLowerCase(); var hours = timeStr.substring(0, timeStr.indexOf(':')); var minutes = timeStr.substring(timeStr.indexOf(':')+1, timeStr.indexOf(' ')); if (meridian=='pm') { hours = (hours=='12') ? '00' : parseInt(hours)+12 ; } else if(hours.length<2) { hours = '0' + hours; } return hours+':'+minutes; } Quote Link to comment https://forums.phpfreaks.com/topic/175104-converting-12-hours-format-to-24-hrs-format/#findComment-923469 Share on other sites More sharing options...
Recommended Posts
Join the conversation
You can post now and register later. If you have an account, sign in now to post with your account.