Changing the 1-24 hour to 1-12 hour for the “getHours()” Method

后端 未结 8 1366
温柔的废话
温柔的废话 2020-12-09 08:57

When I use the \"getHour()\" method in javascript, it displays the military time format. I need it to display the hour in numbers between 1-12 instead. Can anybody tell me

8条回答
  •  感情败类
    2020-12-09 09:48

    getDateTime = () => {
        const today = new Date();
        const day = today.toLocaleDateString('en-us', { weekday: 'short' });
        const month = today.toLocaleString('en-us', { month: 'short' });
        const date = today.getDate()
        const year = today.getFullYear()
        const hours = today.getHours()
        const minutes = today.getMinutes().toString()
        var dayORnight = "AM";
        if (hours > 11) { dayORnight = "PM"; }
        if (hours > 12) { hours = hours - 12; }
        if (hours == 0) { hours = 12; }
        if (hours < 10) { hours = "0" + hours; }
        if (minutes < 10) { minutes = "0" + minutes; }
    
        const datetime = `${day}, ${month} ${date}, ${year} at ${hours}:${minutes} ${dayORnight}`;
        console.log(datetime)
    }
    

提交回复
热议问题