How to get datetime in JavaScript?

前端 未结 7 1100
太阳男子
太阳男子 2020-11-28 03:33

How to get date time in JavaScript with format 31/12/2010 03:55 AM?

7条回答
  •  自闭症患者
    2020-11-28 04:18

    If the format is "fixed" meaning you don't have to use other format you can have pure JavaScript instead of using whole library to format the date:

    //Pad given value to the left with "0"
    function AddZero(num) {
        return (num >= 0 && num < 10) ? "0" + num : num + "";
    }
    
    window.onload = function() {
        var now = new Date();
        var strDateTime = [[AddZero(now.getDate()), 
            AddZero(now.getMonth() + 1), 
            now.getFullYear()].join("/"), 
            [AddZero(now.getHours()), 
            AddZero(now.getMinutes())].join(":"), 
            now.getHours() >= 12 ? "PM" : "AM"].join(" ");
        document.getElementById("Console").innerHTML = "Now: " + strDateTime;
    };

    The variable strDateTime will hold the date/time in the format you desire and you should be able to tweak it pretty easily if you need.

    I'm using join as good practice, nothing more, it's better than adding strings together.

提交回复
热议问题