Friday, May 17, 2024
 Popular · Latest · Hot · Upcoming
172
rated 0 times [  178] [ 6]  / answers: 1 / hits: 18850  / 11 Years ago, tue, july 16, 2013, 12:00:00

I want a js script that converts inputted time to 24 hour format or 12 hour format.



Example,




  • time is entered as 10_10_am result should be:-



    10:10 AM (12 hr format) and 10:10 (24 hr format)


  • time is entered as 10_10_pm result should be:-



    10:10 PM (12 hr format) and 22:10 (24 hr format)



More From » jquery

 Answers
22

HTML



<input type=text id=textbox1/>
<input type=button id=b1 value=convert 12 hr/>
<input type=button id=b2 value=convert 24 hr/>
<div id=result></div>


JS



$(document).ready(function () {
function am_pm_to_hours(time) {
console.log(time);
var hours = Number(time.match(/^(d+)/)[1]);
var minutes = Number(time.match(/:(d+)/)[1]);
var AMPM = time.match(/s(.*)$/)[1];
if (AMPM == pm && hours < 12) hours = hours + 12;
if (AMPM == am && hours == 12) hours = hours - 12;
var sHours = hours.toString();
var sMinutes = minutes.toString();
if (hours < 10) sHours = 0 + sHours;
if (minutes < 10) sMinutes = 0 + sMinutes;
return (sHours +':'+sMinutes);
}

function hours_am_pm(time) {
var hours = time[0] + time[1];
var min = time[2] + time[3];
if (hours < 12) {
return hours + ':' + min + ' AM';
} else {
hours=hours - 12;
hours=(hours.length < 10) ? '0'+hours:hours;
return hours+ ':' + min + ' PM';
}
}
$('#b1').click(function(){
var n = $('#textbox1').val();
var n1 =n.split('_');
var time = hours_am_pm(n1[0]+n1[1]);
$('#result').text(time);
});
$('#b2').click(function(){
var n = $('#textbox1').val();
var n1 =n.split('_');
var time = am_pm_to_hours(n1[0]+':'+n1[1]+' '+n1[2]);
$('#result').text(time);
});

});


Working Demo http://jsfiddle.net/cse_tushar/xEuUR/



updated after Adrian P 's comment



Working Demo http://jsfiddle.net/cse_tushar/xEuUR/4



function hours_am_pm(time) {
var hours = Number(time.match(/^(d+)/)[1]);
var min = Number(time.match(/:(d+)/)[1]);
if (min < 10) min = 0 + min;
if (hours < 12) {
return hours + ':' + min + ' AM';
} else {
hours=hours - 12;
hours=(hours < 10) ? '0'+hours:hours;
return hours+ ':' + min + ' PM';
}
}

[#76967] Monday, July 15, 2013, 11 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
taylert

Total Points: 627
Total Questions: 91
Total Answers: 108

Location: Mayotte
Member since Mon, Sep 12, 2022
2 Years ago
taylert questions
;