如何在JavaScript中获取当前日期?


当前回答

尝试此操作,您可以相应地调整日期格式:

var today = new Date();
var dd = today.getDate();
var mm = today.getMonth() + 1;
var yyyy = today.getFullYear();
if (dd < 10) {
    dd = '0' + dd;
}
if (mm < 10) {
    mm = '0' + mm;
}

var myDate = dd + '-' + mm + '-' + yyyy;

其他回答

这是我目前最喜欢的,因为它既灵活又模块化。它是(至少)三个简单函数的集合:

/**
 * Returns an array with date / time information
 * Starts with year at index 0 up to index 6 for milliseconds
 * 
 * @param {Date} date   date object. If falsy, will take current time.
 * @returns {[]}
 */
getDateArray = function(date) {
    date = date || new Date();
    return [
        date.getFullYear(),
        exports.pad(date.getMonth()+1, 2),
        exports.pad(date.getDate(), 2),
        exports.pad(date.getHours(), 2),
        exports.pad(date.getMinutes(), 2),
        exports.pad(date.getSeconds(), 2),
        exports.pad(date.getMilliseconds(), 2)
    ];
};

下面是pad函数:

 /**
 * Pad a number with n digits
 *
 * @param {number} number   number to pad
 * @param {number} digits   number of total digits
 * @returns {string}
 */
exports.pad = function pad(number, digits) {
    return new Array(Math.max(digits - String(number).length + 1, 0)).join(0) + number;
};

最后,我可以手动创建日期字符串,也可以使用一个简单的函数来实现:

/**
 * Returns nicely formatted date-time
 * @example 2015-02-10 16:01:12
 *
 * @param {object} date
 * @returns {string}
 */
exports.niceDate = function(date) {
    var d = exports.getDateArray(date);
    return d[0] + '-' + d[1] + '-' + d[2] + ' ' + d[3] + ':' + d[4] + ':' + d[5];
};

/**
 * Returns a formatted date-time, optimized for machines
 * @example 2015-02-10_16-00-08
 *
 * @param {object} date
 * @returns {string}
 */
exports.roboDate = function(date) {
    var d = exports.getDateArray(date);
    return d[0] + '-' + d[1] + '-' + d[2] + '_' + d[3] + '-' + d[4] + '-' + d[5];
};

这是一个很好的格式化日期

let date=new date().toLocaleDateString(“en”,{年:“numeric”,日:“2位数”,月:“2位”});console.log(日期);

如果您正在使用jQuery。试试这一行:

$.datepicker.formatDate('dd/mm/yy', new Date());

以下是格式化日期的惯例

d-月份的日期(无前导零)dd-月份的日期(两位数)o-一年中的某一天(无前导零)oo-一年中的一天(三位数)D-天名称缩写DD-日名称长m-一年中的月份(无前导零)mm-一年中的月份(两位数)M-月名缩写MM-月份名称长y-年(两位数)yy-年(四位数)

以下是jQuery日期选择器的参考

如果您想要对日期格式进行更精细的控制,我强烈建议您查看momentjs。非常棒的图书馆-只有5KB。http://momentjs.com/

试用Date.js

毫秒

date.js.millisecond(); // 0.00

date.js.second(); // 58

分钟

date.js.minute(); // 31

小时

date.js.hour(); // 6  (PM)

Days

date.js.day(); // Monday

date.js.week(); // (Week Of the Month / WOM) => 2

date.js.month(); // (Month) => November

TLM(三字母月)

date.js.tlmonth(); // (Month) => Dec

Year

date.js.year(); // (Year / String: "") => "2021"

date.js.season(); // (Fall / Season: seasons) => "fall"

当前时间(AM/PM)

date.js.time(); // (Time / Zone: "PDT/EDT etc.") => 10:04 AM