简体   繁体   中英

How to Convert Date/Time Display from 24hr to 12hr AM/PM

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>

Try this.

function hours12(date) { 
   return (date.getHours() + 24) % 12 || 12; 
}

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

So simple try this

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

    getAmPm(hours: any) {
        return (hours < 12) ? "am" : "pm";
    };

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM