I don't know how to change time format 24hrs to 12hrs format

function formatAMPM() {
    var d = new Date(),
        minutes = d.getMinutes().toString().length == 1 ? '0'+d.getMinutes() : d.getMinutes(),
        hours = d.getHours().toString().length == 1 ? '0'+d.getHours() : d.getHours(),
        ampm = d.getHours() >= 12 ? 'pm' : 'am',
        months = ['Jan','Feb','Mar','Apr','May','Jun','Jul','Aug','Sep','Oct','Nov','Dec'],
        days = ['Sun','Mon','Tue','Wed','Thu','Fri','Sat'];
    return days[d.getDay()]+' '+d.getDate()+' '+months[d.getMonth()]+' '+d.getFullYear()+' '+hours+':'+minutes+ampm;
}

how to change time format this code.

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’m not using textbox only i use div

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';
        }

This topic was automatically closed 91 days after the last reply. New replies are no longer allowed.