Please use this format for your Javascript queries
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);
});
});
I haven’t done much with javascript, but I’m not sure your conditions in hours_am_pm() will produce the correct answer for some time periods, and that’s only because I’ve recently had to write some code that runs the other way around.
Consider 00:30 as a time, half an hour after midnight. In 12-hour clock, I think that should be “12:30AM”, but I think your function, if I am reading it correctly, will give “00:30 AM”. Same for 12:30, your function will return “00:30 PM”, instead of “12:30 PM”. Also, doesn’t hours.length in your example return either 1 or 2, so when you check if it’s less than 10, you’ll always be preceding it with a zero, so in fact at “23:30” it will say “011:30 PM” instead of “11:30 PM”.
Maybe:
function hours_am_pm(time) {
var hours = time[0] + time[1];
var min = time[2] + time[3];
if (hours < 12) {
if (hours==0) hours = 12;
return hours + ':' + min + ' AM';
} else {
if (hours > 12) hours -= 12;
hours=(hours < 10) ? '0'+hours:hours;
return hours+ ':' + min + ' PM';
}