如何在12小时内检索当前的“DateTime”?

时间:2011-12-16 19:00:11

标签: javascript datetime

将当前日期时间作为字符串从JavaScript格式化为:

的最佳方法是什么
11/5/2011 1:56:44 PM

而不是(24小时/“军事”时间)

11/5/2011 13:56:44

3 个答案:

答案 0 :(得分:4)

演示:http://jsfiddle.net/k6g4g/

var date = new Date,
    day = date.getDate(),
    month = date.getMonth() + 1,
    year = date.getFullYear(),
    hour = date.getHours(),
    minute = date.getMinutes(),
    seconds = date.getSeconds(),
    ampm = hour > 12 ? "PM" : "AM";

hour = hour % 12;
hour = hour ? hour : 12; // zero = 12

minute = minute > 9 ? minute : "0" + minute;
seconds = seconds > 9 ? seconds : "0" + seconds;
hour = hour > 9 ? hour : "0" + hour;


date = month + "/" + day + "/" + year + " " + hour + ":" + minute + ":" + seconds + " " + ampm;
// date holds "12/16/2011 08:14:30 PM"

答案 1 :(得分:1)

以下链接有一个formatDate()方法可以帮助您:

http://www.mattkruse.com/javascript/date/

答案 2 :(得分:0)

您可以在返回之前使用它来格式化它。

function formatTime(time, options) {
            month_names = ["January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December"];
            var a_p = "";
            var Time = {};
            Time.hour = new Date(time).getHours(); //military time?
            if (Time.hour < 12) {
                a_p = "AM";
            } else {
                Time.hour = Time.hour - 12;
                a_p = "PM";
            }
            Time.minute = new Date(time).getMinutes();
            Time.minute = Time.minute + "";
            if (Time.minute.length == 1) {
                Time.minute = "0" + Time.minute
            }
            Time.month = new Date(time).getMonth();
            Time.month = month_names[Time.month];
            Time.date = new Date(time).getDate();
            Time.year = new Date(time).getFullYear();
            formattedTime = Time.month + ' ' + Time.date + ', ' + Time.year + ' &#8212; ' + Time.hour + ':' + Time.minute + a_p;
            return formattedTime
        }