如何在JavaScript中获取日期时间?


Answers:


155

从语义上讲,您可能正在寻找一线客

new Date().toLocaleString()

会在用户的语言环境中格式化日期。

如果您确实在寻找一种格式化日期的特定方法,则建议使用moment.js库。


3
感谢您推荐moment.js库;这是梦幻般的。
carbontwelve

3
没有人应该编写自己的日期/时间代码(如其他一些答案所示)。极端案例的数量惊人。去看一下moment.js的单元测试页面(momentjs.com/tests)——有66701个测试!只需使用它,那就太好了。或者找到另一个库,但是不要为此编写自己的代码,您很可能会错过一些东西(我过去曾把它弄得一团糟)。
sidewinderguy 2016年

1
我不明白为什么很难找到一个行之有效的答案。谢谢。
timhc22 '16

46

如果格式是“固定的”,则意味着您不必使用其他格式,则可以使用纯JavaScript而不是使用整个库来格式化日期:

//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;
};
<div id="Console"></div>

该变量strDateTime将以您想要的格式保存日期/时间,并且您应该可以根据需要轻松地对其进行调整。

我使用的join是一种很好的做法,仅此而已,这比将字符串加在一起更好。


@Jens是的,这是尽可能的标准,很难相信任何浏览器对于基本的日期/时间方法都会有不同的语法。:)
暗影巫师为您耳边

2
很好的解决方案,对于使用格式,也只需交换AddZero(now.getDate())和AddZero(now.getMonth()+ 1)语句,然后将小时数调整为0(如果为0,则为12,如果大于12,则为-12)。祝你好运,并感谢您的解决方案
Gent

您的代码应返回02:45 PM,而不是14:45 PM。因此,我对您的代码进行了一些修改:function getNowDateTimeStr(){var now = new Date(); var hour = now.getHours()-(now.getHours()> = 12?12:0)); 返回[[AddZero(now.getDate()),AddZero(now.getMonth()+ 1),now.getFullYear()]。join(“ /”),[AddZero(hour),AddZero(now.getMinutes() )]。join(“:”),now.getHours()> = 12吗?“ PM”:“ AM”]。join(“”); } //使用“ 0”函数将给定值填充到左侧AddZero(num){return(num> = 0 && num <10)吗?“ 0” + num:num +“”; }
dalmate


9

Date().toLocaleString() 返回此: 7/31/2018, 12:58:03 PM

非常接近-只需删除逗号和秒数即可:

new Date().toLocaleString().replace(",","").replace(/:.. /," ");

结果: 7/31/2018 12:58 PM


5
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);
}

截至2012年9月3日10:11,代码已更正


检查您的工作。我尝试了此操作,并获得了“ 03/06/112 05:02 PM”作为输出。时间里只有正确的东西。日期,月份和(显然)年份都不正确。
Muhd 2012年

5

您可以使用下面添加的代码片段将Date转换为几乎任何格式。

码:

dateFormat(new Date(),"dd/mm/yy h:MM TT")
//"20/06/14 6:49 PM"

其他例子

// Can also be used as a standalone function
dateFormat(new Date(), "dddd, mmmm dS, yyyy, h:MM:ss TT");
// Saturday, June 9th, 2007, 5:46:21 PM

dateFormat(new Date(),"dddd d mmmm yyyy")
//Monday 2 June 2014"

片段

将从此链接中获取的以下代码添加到您的代码中。

var dateFormat = function () {
    var token = /d{1,4}|m{1,4}|yy(?:yy)?|([HhMsTt])\1?|[LloSZ]|"[^"]*"|'[^']*'/g,
        timezone = /\b(?:[PMCEA][SDP]T|(?:Pacific|Mountain|Central|Eastern|Atlantic) (?:Standard|Daylight|Prevailing) Time|(?:GMT|UTC)(?:[-+]\d{4})?)\b/g,
        timezoneClip = /[^-+\dA-Z]/g,
        pad = function (val, len) {
            val = String(val);
            len = len || 2;
            while (val.length < len) val = "0" + val;
            return val;
        };

    // Regexes and supporting functions are cached through closure
    return function (date, mask, utc) {
        var dF = dateFormat;

        // You can't provide utc if you skip other args (use the "UTC:" mask prefix)
        if (arguments.length == 1 && Object.prototype.toString.call(date) == "[object String]" && !/\d/.test(date)) {
            mask = date;
            date = undefined;
        }

        // Passing date through Date applies Date.parse, if necessary
        date = date ? new Date(date) : new Date;
        if (isNaN(date)) throw SyntaxError("invalid date");

        mask = String(dF.masks[mask] || mask || dF.masks["default"]);

        // Allow setting the utc argument via the mask
        if (mask.slice(0, 4) == "UTC:") {
            mask = mask.slice(4);
            utc = true;
        }

        var _ = utc ? "getUTC" : "get",
            d = date[_ + "Date"](),
            D = date[_ + "Day"](),
            m = date[_ + "Month"](),
            y = date[_ + "FullYear"](),
            H = date[_ + "Hours"](),
            M = date[_ + "Minutes"](),
            s = date[_ + "Seconds"](),
            L = date[_ + "Milliseconds"](),
            o = utc ? 0 : date.getTimezoneOffset(),
            flags = {
                d:    d,
                dd:   pad(d),
                ddd:  dF.i18n.dayNames[D],
                dddd: dF.i18n.dayNames[D + 7],
                m:    m + 1,
                mm:   pad(m + 1),
                mmm:  dF.i18n.monthNames[m],
                mmmm: dF.i18n.monthNames[m + 12],
                yy:   String(y).slice(2),
                yyyy: y,
                h:    H % 12 || 12,
                hh:   pad(H % 12 || 12),
                H:    H,
                HH:   pad(H),
                M:    M,
                MM:   pad(M),
                s:    s,
                ss:   pad(s),
                l:    pad(L, 3),
                L:    pad(L > 99 ? Math.round(L / 10) : L),
                t:    H < 12 ? "a"  : "p",
                tt:   H < 12 ? "am" : "pm",
                T:    H < 12 ? "A"  : "P",
                TT:   H < 12 ? "AM" : "PM",
                Z:    utc ? "UTC" : (String(date).match(timezone) || [""]).pop().replace(timezoneClip, ""),
                o:    (o > 0 ? "-" : "+") + pad(Math.floor(Math.abs(o) / 60) * 100 + Math.abs(o) % 60, 4),
                S:    ["th", "st", "nd", "rd"][d % 10 > 3 ? 0 : (d % 100 - d % 10 != 10) * d % 10]
            };

        return mask.replace(token, function ($0) {
            return $0 in flags ? flags[$0] : $0.slice(1, $0.length - 1);
        });
    };
}();

// Some common format strings
dateFormat.masks = {
    "default":      "ddd mmm dd yyyy HH:MM:ss",
    shortDate:      "m/d/yy",
    mediumDate:     "mmm d, yyyy",
    longDate:       "mmmm d, yyyy",
    fullDate:       "dddd, mmmm d, yyyy",
    shortTime:      "h:MM TT",
    mediumTime:     "h:MM:ss TT",
    longTime:       "h:MM:ss TT Z",
    isoDate:        "yyyy-mm-dd",
    isoTime:        "HH:MM:ss",
    isoDateTime:    "yyyy-mm-dd'T'HH:MM:ss",
    isoUtcDateTime: "UTC:yyyy-mm-dd'T'HH:MM:ss'Z'"
};

// Internationalization strings
dateFormat.i18n = {
    dayNames: [
        "Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat",
        "Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday"
    ],
    monthNames: [
        "Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec",
        "January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December"
    ]
};

// For convenience...
Date.prototype.format = function (mask, utc) {
    return dateFormat(this, mask, utc);
};

1

@Shadow向导的代码应返回02:45 PM,而不是14:45 PM。所以我修改了他的代码:

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 + "";
}
By using our site, you acknowledge that you have read and understand our Cookie Policy and Privacy Policy.
Licensed under cc by-sa 3.0 with attribution required.