0

The following script works well to display the date and time in a 24 hr format. I'd like to convert it to display time in a 12 hr AM/PM format instead and I can't get it to work. Please show me how it's done correctly?

<script type="text/javascript">
    function date_time(id) {
        date = new Date;
        year = date.getFullYear();
        month = date.getMonth();
        months = new Array('Jan', 'Feb', 'Mar', 'Apr', 'May', 'June', 'July', 'Aug', 'Sept', 'Oct', 'Nov', 'Dec');
        d = date.getDate();
        day = date.getDay();
        days = new Array('Sun', 'Mon, ', 'Tues, ', 'Wed, ', 'Thu, ', 'Fri, ', 'Sat');
        h = date.getHours();

        if (h < 10) {
            h = "0" + h;
        }

        m = date.getMinutes();

        if (m < 10) {
            m = "0" + m;
        }

        s = date.getSeconds();

        if (s < 10) {
            s = "0" + s;
        }

        result = '' + days[day] + ' ' + months[month] + ' ' + d + ' <br>' + h + ':' + m + ' ' + year + ':' + s;
        document.getElementById(id).innerHTML = result;
        setTimeout('date_time("' + id + '");', '1000');

        return true;
    }
</script>
Fcmam5
  • 4,888
  • 1
  • 16
  • 33
  • @Sebastian Thanks for you reply, but I think I can learn more this way. It isn't just the outcome I'm looking for. –  Dec 18 '19 at 10:27
  • This may helps you: https://stackoverflow.com/questions/13898423/javascript-convert-24-hour-time-of-day-string-to-12-hour-time-with-am-pm-and-no – Maximilian Fixl Dec 18 '19 at 10:44

3 Answers3

0

Try this.

function hours12(date) { 
   return (date.getHours() + 24) % 12 || 12; 
}
Sebastian Kaczmarek
  • 8,120
  • 4
  • 20
  • 38
Prathamesh Doke
  • 797
  • 2
  • 16
  • 38
0

Update your function to:

function date_time(id) {
    date = new Date();
    year = date.getFullYear();
    month = date.getMonth();
    months = new Array('Jan', 'Feb', 'Mar', 'Apr', 'May', 'June', 'July', 'Aug', 'Sept', 'Oct', 'Nov', 'Dec');
    d = date.getDate();
    day = date.getDay();
    days = new Array('Sun', 'Mon, ', 'Tues, ', 'Wed, ', 'Thu, ', 'Fri, ', 'Sat');
    h = date.getHours();
    if (h < 10) {
        h = "0" + h;
    }
    m = date.getMinutes();
    if (m < 10) {
        m = "0" + m;
    }
    s = date.getSeconds();
    if (s < 10) {
        s = "0" + s;
    }
    const pmOrAm = h > 12 ? "pm" : "am";
    const hoursIn12 = h > 12 ? h - 12 : h;
    result = '' + days[day] + ' ' + months[month] + ' ' + d + ' <br>' + hoursIn12 + ':' + m + pmOrAm + ' ' + year + ':' + s;

    document.getElementById(id).innerHTML = result;
    setTimeout('date_time("' + id + '");', '1000');
    return true;
}
Ali Torki
  • 1,929
  • 16
  • 26
0

So simple try this

   from24to12(hours: any) {
        return (hours > 12) ? hours - 12 : (hours == 0 ? 12 : hours);
    };

    getAmPm(hours: any) {
        return (hours < 12) ? "am" : "pm";
    };
Vasim Hayat
  • 909
  • 11
  • 16