如何格式化 JavaScript 日期

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/3552461/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-23 05:09:07  来源:igfitidea点击:

How to format a JavaScript date

javascriptdatedate-formatting

提问by leora

In JavaScript, how can I format a date object to print as 10-Aug-2010?

在 JavaScript 中,如何格式化要打印的日期对象10-Aug-2010

采纳答案by Marko

For custom-delimited date formats, you have to pull out the date (or time) components from a DateTimeFormatobject (which is part of the ECMAScript Internationalization API), and then manually create a string with the delimiters you want.

对于自定义分隔的日期格式,您必须从DateTimeFormat对象(它是ECMAScript 国际化 API 的一部分)中提取日期(或时间)组件,然后手动创建带有所需分隔符的字符串。

To do this, you can use DateTimeFormat#formatToParts:

为此,您可以使用DateTimeFormat#formatToParts

const date = new Date('2010-08-05')
const dateTimeFormat = new Intl.DateTimeFormat('en', { year: 'numeric', month: 'short', day: '2-digit' }) 
const [{ value: month },,{ value: day },,{ value: year }] = dateTimeFormat .formatToParts(date ) 

console.log(`${day}-${month}-${year }`)
console.log(`${day}${month}${year}`) // just for fun

You can also pull out the parts of a DateTimeFormatone-by-one using DateTimeFormat#format, but note that when using this method, as of March 2020, there is a bugin the ECMAScript implementation when it comes to leading zeros on minutes and seconds (this bug is circumvented by the approach above).

您也可以使用DateTimeFormat逐一拉出部分DateTimeFormat#format,但请注意,使用此方法时,截至 2020 年 3 月,ECMAScript 实现中存在一个错误,涉及分钟和秒前导零(此错误被上述方法规避)。

const d = new Date('2010-08-05')
const ye = new Intl.DateTimeFormat('en', { year: 'numeric' }).format(d)
const mo = new Intl.DateTimeFormat('en', { month: 'short' }).format(d)
const da = new Intl.DateTimeFormat('en', { day: '2-digit' }).format(d)

console.log(`${da}-${mo}-${ye}`)

When working with dates and times, it is usually worth using a library (eg. moment.js, luxon) because of the many hidden complexities of the field.

在处理日期和时间时,通常值得使用库(例如moment.jsluxon),因为该领域有许多隐藏的复杂性。

Note that the ECMAScript Internationalization API, used in the solutions above is not supported in IE10(0.03%global browser market share in Feb 2020).

请注意,IE10不支持上述解决方案中使用的 ECMAScript 国际化 API (2020 年 2 月全球浏览器市场份额为0.03%)。

回答by ajeet kanojia

If you need slightly less control over formatting than the currently accepted answer, Date#toLocaleDateStringcan be used to create standard locale-specific renderings. The localeand optionsarguments let applications specify the language whose formatting conventions should be used, and allow some customization of the rendering.

如果您需要对格式的控制比当前接受的答案稍少,Date#toLocaleDateString可用于创建标准的特定于语言环境的渲染。在localeoptions论据让应用程序指定其格式约定应该使用的语言,并允许渲染的一些定制。

Options key examples:

选项关键示例:

  1. day:
    The representation of the day.
    Possible values are "numeric", "2-digit".
  2. weekday:
    The representation of the weekday.
    Possible values are "narrow", "short", "long".
  3. year:
    The representation of the year.
    Possible values are "numeric", "2-digit".
  4. month:
    The representation of the month.
    Possible values are "numeric", "2-digit", "narrow", "short", "long".
  5. hour:
    The representation of the hour.
    Possible values are "numeric", "2-digit".
  6. minute:The representation of the minute.
    Possible values are "numeric", "2-digit".
  7. second:
    The representation of the second.
    Possible values are "numeric", 2-digit".
  1. day:一天
    的表示。
    可能的值为“数字”、“2 位数字”。
  2. 工作日:工作日
    的表示。
    可能的值为“窄”、“短”、“长”。
  3. 年份:年份
    的表示。
    可能的值为“数字”、“2 位数字”。
  4. 月份:月份
    的表示。
    可能的值为“数字”、“2 位”、“窄”、“短”、“长”。
  5. 小时:小时
    的表示。
    可能的值为“数字”、“2 位数字”。
  6. 分钟:分钟的表示。
    可能的值为“数字”、“2 位数字”。
  7. 第二:第二
    的表示。
    可能的值是“数字”,2 位数字。

All these keys are optional. You can change the number of options values based on your requirements, and this will also reflect the presence of each date time term.

所有这些键都是可选的。您可以根据您的要求更改选项值的数量,这也将反映每个日期时间项的存在。

Note: If you would only like to configure the content options, but still use the current locale, passing nullfor the first parameter will cause an error. Use undefinedinstead.

注意:如果您只想配置内容选项,但仍使用当前语言环境,则传递null第一个参数会导致错误。使用undefined来代替。

For different languages:

对于不同的语言:

  1. "en-US":For English
  2. "hi-IN":For Hindi
  3. "ja-JP":For Japanese
  1. “en-US”:英语
  2. “hi-IN”:对于印地语
  3. “ja-JP”:日语

You can use more language options.

您可以使用更多语言选项。

For example

例如

var options = { weekday: 'long', year: 'numeric', month: 'long', day: 'numeric' };
var today  = new Date();

console.log(today.toLocaleDateString("en-US")); // 9/17/2016
console.log(today.toLocaleDateString("en-US", options)); // Saturday, September 17, 2016
console.log(today.toLocaleDateString("hi-IN", options)); // ??????, 17 ?????? 2016

You can also use the toLocaleString()method for the same purpose. The only difference is this function provides the time when you don't pass any options.

您也可以将该toLocaleString()方法用于相同目的。唯一的区别是此函数提供您不传递任何选项的时间。

// Example
9/17/2016, 1:21:34 PM

References:

参考:

回答by RobertPitt

Use the date.format library:

使用date.format 库

var dateFormat = require('dateformat');
var now = new Date();
dateFormat(now, "dddd, mmmm dS, yyyy, h:MM:ss TT");

returns:

返回:

Saturday, June 9th, 2007, 5:46:21 PM 

dateformat on npm

npm 上的日期格式

http://jsfiddle.net/phZr7/1/

http://jsfiddle.net/phZr7/1/

回答by sebastian.i

If you need to quickly format your date using plain JavaScript, use getDate, getMonth + 1, getFullYear, getHoursand getMinutes:

如果你需要使用普通的JavaScript,使用快速格式化你的日期getDategetMonth + 1getFullYeargetHoursgetMinutes

var d = new Date();

var datestring = d.getDate()  + "-" + (d.getMonth()+1) + "-" + d.getFullYear() + " " +
d.getHours() + ":" + d.getMinutes();

// 16-5-2015 9:50

Or, if you need it to be padded with zeros:

或者,如果您需要用零填充它:

var datestring = ("0" + d.getDate()).slice(-2) + "-" + ("0"+(d.getMonth()+1)).slice(-2) + "-" +
    d.getFullYear() + " " + ("0" + d.getHours()).slice(-2) + ":" + ("0" + d.getMinutes()).slice(-2);

// 16-05-2015 09:50

回答by simo

Well, what I wanted was to convert today's date to a MySQLfriendly date string like 2012-06-23, and to use that string as a parameter in one of my queries. The simple solution I've found is this:

好吧,我想要的是将今天的日期转换为MySQL友好的日期字符串,如 2012-06-23,并在我的一个查询中使用该字符串作为参数。我发现的简单解决方案是这样的:

var today = new Date().toISOString().slice(0, 10);

Keep in mind that the above solution does nottake into account your timezone offset.

请记住,上面的解决方案并没有考虑到你的时区偏移。

You might consider using this function instead:

您可以考虑改用此函数:

function toJSONLocal (date) {
    var local = new Date(date);
    local.setMinutes(date.getMinutes() - date.getTimezoneOffset());
    return local.toJSON().slice(0, 10);
}

This will give you the correct date in case you are executing this code around the start/end of the day.

如果您在一天的开始/结束前后执行此代码,这将为您提供正确的日期。

回答by Adrian Maire

Custom formatting function:

自定义格式化功能:

For fixed formats, a simple function make the job. The following example generates the international format YYYY-MM-DD:

对于固定格式,一个简单的函数就可以完成工作。以下示例生成国际格式 YYYY-MM-DD:

function dateToYMD(date) {
    var d = date.getDate();
    var m = date.getMonth() + 1; //Month from 0 to 11
    var y = date.getFullYear();
    return '' + y + '-' + (m<=9 ? '0' + m : m) + '-' + (d <= 9 ? '0' + d : d);
}

console.log(dateToYMD(new Date(2017,10,5))); // Nov 5

The OP format may be generated like:

OP 格式可以像这样生成:

function dateToYMD(date) {
    var strArray=['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec'];
    var d = date.getDate();
    var m = strArray[date.getMonth()];
    var y = date.getFullYear();
    return '' + (d <= 9 ? '0' + d : d) + '-' + m + '-' + y;
}
console.log(dateToYMD(new Date(2017,10,5))); // Nov 5

Note: It is, however, usually not a good idea to extend the JavaScript standard libraries (e.g. by adding this function to the prototype of Date).

注意:然而,扩展 JavaScript 标准库通常不是一个好主意(例如通过将此函数添加到 Date 的原型)。

A more advanced function could generate configurable output based on a format parameter.

更高级的功能可以根据格式参数生成可配置的输出。

If to write a formatting function is too long, there are plenty of libraries around which does it. Some other answers already enumerate them. But increasing dependencies also has it counter-part.

如果编写格式化函数太长,有很多库可以做。其他一些答案已经列举了它们。但增加依赖也有它的对应部分。

Standard ECMAScript formatting functions:

标准的 ECMAScript 格式化函数:

Since more recent versions of ECMAScript, the Dateclass has some specific formatting functions:

由于 ECMAScript 的更新版本,Date该类具有一些特定的格式化功能:

toDateString: Implementation dependent, show only the date.

http://www.ecma-international.org/ecma-262/7.0/index.html#sec-date.prototype.todatestring

new Date().toDateString(); // e.g. "Fri Nov 11 2016"

toDateString:依赖于实现,只显示日期。

http://www.ecma-international.org/ecma-262/7.0/index.html#sec-date.prototype.todatestring

new Date().toDateString(); // e.g. "Fri Nov 11 2016"


toISOString: Show ISO 8601 date and time.

http://www.ecma-international.org/ecma-262/7.0/index.html#sec-date.prototype.toisostring

new Date().toISOString(); // e.g. "2016-11-21T08:00:00.000Z"

toISOString:显示 ISO 8601 日期和时间。

http://www.ecma-international.org/ecma-262/7.0/index.html#sec-date.prototype.toisostring

new Date().toISOString(); // e.g. "2016-11-21T08:00:00.000Z"


toJSON: Stringifier for JSON.

http://www.ecma-international.org/ecma-262/7.0/index.html#sec-date.prototype.tojson

new Date().toJSON(); // e.g. "2016-11-21T08:00:00.000Z"

toJSON: JSON 的字符串化符。

http://www.ecma-international.org/ecma-262/7.0/index.html#sec-date.prototype.tojson

new Date().toJSON(); // e.g. "2016-11-21T08:00:00.000Z"


toLocaleDateString: Implementation dependent, a date in locale format.

http://www.ecma-international.org/ecma-262/7.0/index.html#sec-date.prototype.tolocaledatestring

new Date().toLocaleDateString(); // e.g. "21/11/2016"

toLocaleDateString:依赖于实现,区域设置格式的日期。

http://www.ecma-international.org/ecma-262/7.0/index.html#sec-date.prototype.tolocaledatestring

new Date().toLocaleDateString(); // e.g. "21/11/2016"


toLocaleString: Implementation dependent, a date&time in locale format.

http://www.ecma-international.org/ecma-262/7.0/index.html#sec-date.prototype.tolocalestring

new Date().toLocaleString(); // e.g. "21/11/2016, 08:00:00 AM"

toLocaleString:依赖于实现,区域设置格式的日期和时间。

http://www.ecma-international.org/ecma-262/7.0/index.html#sec-date.prototype.tolocalestring

new Date().toLocaleString(); // e.g. "21/11/2016, 08:00:00 AM"


toLocaleTimeString: Implementation dependent, a time in locale format.

http://www.ecma-international.org/ecma-262/7.0/index.html#sec-date.prototype.tolocaletimestring

new Date().toLocaleTimeString(); // e.g. "08:00:00 AM"

toLocaleTimeString:依赖于实现,区域设置格式的时间。

http://www.ecma-international.org/ecma-262/7.0/index.html#sec-date.prototype.tolocaletimestring

new Date().toLocaleTimeString(); // e.g. "08:00:00 AM"


toString: Generic toString for Date.

http://www.ecma-international.org/ecma-262/7.0/index.html#sec-date.prototype.tostring

new Date().toString(); // e.g. "Fri Nov 21 2016 08:00:00 GMT+0100 (W. Europe Standard Time)"

toString:Date 的通用 toString。

http://www.ecma-international.org/ecma-262/7.0/index.html#sec-date.prototype.tostring

new Date().toString(); // e.g. "Fri Nov 21 2016 08:00:00 GMT+0100 (W. Europe Standard Time)"

Note: it is possible to generate custom output out of those formatting >

注意:可以从这些格式中生成自定义输出 >

new Date().toISOString().slice(0,10); //return YYYY-MM-DD
new Date().toISOString().slice(0,10); //return YYYY-MM-DD

Examples snippets:

示例片段:

console.log("1) "+  new Date().toDateString());
console.log("2) "+  new Date().toISOString());
console.log("3) "+  new Date().toJSON());
console.log("4) "+  new Date().toLocaleDateString());
console.log("5) "+  new Date().toLocaleString());
console.log("6) "+  new Date().toLocaleTimeString());
console.log("7) "+  new Date().toString());
console.log("8) "+  new Date().toISOString().slice(0,10));

回答by Dmitry Pavlov

If you are already using jQuery UIin your project you could do it this way:

如果你已经在你的项目中使用 jQuery UI,你可以这样做:

var formatted = $.datepicker.formatDate("M d, yy", new Date("2014-07-08T09:02:21.377"));

// formatted will be 'Jul 8, 2014'

Some datepicker date format options to play with are available here.

此处提供了一些可供使用的 datepicker 日期格式选项。

回答by Sébastien

I think you can just use the non-standardDate method toLocaleFormat(formatString)

我认为你可以使用非标准的Date 方法toLocaleFormat(formatString)

formatString:A format string in the same format expected by the strftime()function in C.

formatString:strftime()C 中的函数所期望的格式相同的格式字符串。

var today = new Date();
today.toLocaleFormat('%d-%b-%Y'); // 30-Dec-2011

References:

参考:

回答by Mite Mitreski

Plain JavaScript is the best pick for small onetimers.

纯 JavaScript 是小型一次性的最佳选择。

On the other hand, if you need more date stuff, MomentJSis a great solution.

另一方面,如果你需要更多的约会内容,MomentJS是一个很好的解决方案。

For example:

例如:

moment().format('YYYY-MM-DD HH:m:s');     // now() -> 2015-03-24 14:32:20
moment("20111031", "YYYYMMDD").fromNow(); // 3 years ago
moment("20120620", "YYYYMMDD").fromNow(); // 3 years ago
moment().startOf('day').fromNow();        // 11 hours ago
moment().endOf('day').fromNow();          // in 13 hours

回答by John Slegers

In modern browsers (*), you can just do this:

在现代浏览器(*) 中,您可以这样做:

var today = new Date().toLocaleDateString('en-GB', {
    day : 'numeric',
    month : 'short',
    year : 'numeric'
}).split(' ').join('-');

Output if executed today (january 24??, 2016):

如果今天(2016 年 1 月 24 日??,2016 年)执行,则输出:

'24-Jan-2016'


(*)According to MDN, "modern browsers" means Chrome 24+, Firefox 29+, Internet Explorer 11, Edge 12+, Opera 15+ & Safari nightly build.

(*)根据 MDN,“现代浏览器”是指 Chrome 24+、Firefox 29+、Internet Explorer 11、Edge 12+、Opera 15+ 和 Safari nightly build