How to get datetime in JavaScript?

前端 未结 7 1105
太阳男子
太阳男子 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:14

    @Shadow Wizard's code should return 02:45 PM instead of 14:45 PM. So I modified his code a bit:

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

提交回复
热议问题