How to get datetime in JavaScript?

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

    function pad_2(number)
    {
         return (number < 10 ? '0' : '') + number;
    }
    
    function hours(date)
    {
        var hours = date.getHours();
        if(hours > 12)
            return hours - 12; // Substract 12 hours when 13:00 and more
        return hours;
    }
    
    function am_pm(date)
    {
        if(date.getHours()==0 && date.getMinutes()==0 && date.getSeconds()==0)
            return ''; // No AM for MidNight
        if(date.getHours()==12 && date.getMinutes()==0 && date.getSeconds()==0)
            return ''; // No PM for Noon
        if(date.getHours()<12)
            return ' AM';
        return ' PM';
    }
    
    function date_format(date)
    {
         return pad_2(date.getDate()) + '/' +
                pad_2(date.getMonth()+1) + '/' +
                (date.getFullYear() + ' ').substring(2) +
                pad_2(hours(date)) + ':' +
                pad_2(date.getMinutes()) +
                am_pm(date);
    }
    

    Code corrected as of Sep 3 '12 at 10:11

提交回复
热议问题