ChatGPT解决这个技术问题 Extra ChatGPT

如何在 JavaScript 中格式化日期?

如何将 Date 对象格式化为字符串?

像往常一样:当心这个月是零索引的!所以一月是零而不是一...
另请注意,myDate.getDay() 不会返回星期几,而是返回与星期相关的工作日位置myDate.getDate() 返回当前工作日
您可以使用 toLocaleDateString
如果您正在寻找如何将字符串解析为 Date 对象,请参阅 Parsing a string to a date in JavaScript

P
Prid

如果您需要比当前接受的答案稍微少一点的格式控制,Date#toLocaleDateString 可用于创建标准区域设置特定的呈现。 localeoptions 参数让应用程序指定应使用其格式约定的语言,并允许对呈现进行一些自定义。

选项关键示例:

日:一天的表示。可能的值为“数字”、“2 位”。 weekday:表示工作日。可能的值是“窄”、“短”、“长”。年份:年份的表示。可能的值为“数字”、“2 位”。月:月份的表示。可能的值是“numeric”、“2-digit”、“narrow”、“short”、“long”。小时:小时的表示。可能的值为“数字”、“2 位”。分钟:分钟的表示。可能的值为“数字”、“2 位”。 second:第二个的表示。可能的值为“数字”、2 位数字。

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

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

对于不同的语言:

“en-US”:美式英语 “en-GB”:英式英语 “hi-IN”:印地语 “ja-JP”:日语

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

例如

var options = { weekday: 'long', year: 'numeric', month: 'long', day: 'numeric' }; var 今天 = 新日期(); console.log(today.toLocaleDateString("en-US")); // 9/17/2016 console.log(today.toLocaleDateString("en-US", options)); // 2016 年 9 月 17 日星期六 console.log(today.toLocaleDateString("hi-IN", options)); // शनिवार, 17 सितंबर 2016

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

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

参考:

toLocaleString()

toLocaleDateString()


this 说它是非标准的,但 mozzilla 没有具体说明
似乎这个答案应该是最好的“当前”答案。还使用选项“hour12: true”来使用 12 小时制与 24 小时制格式。也许应该在答案中添加到您的摘要列表中。
@Iarwa1n 此答案未提及,但您可以使用 toLocaleDateString 仅返回某些部分,然后您可以根据需要加入这些部分。在下面检查我的答案。 date.toLocaleDateString("en-US", { day: 'numeric' }) + "-"+ date.toLocaleDateString("en-US", { month: 'short' }) + "-" + date.toLocaleDateString("en-US", { year: 'numeric' }) 应该给 16-Nov-2019
对以下链接进行了长时间的挖掘,但我发现了它们的隐藏位置@MosesSchwartz:developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/…
@KVij - 这是格式化日期的一种非常低效的方法,特别是考虑到有一个 formatToParts method 返回对象数组中的所有部分。
Z
Zombo

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

为此,您可以使用 DateTimeFormat#formatToParts。您可以解构数组,但这并不理想,因为数组输出取决于语言环境:

{ // 示例 1 let f = new Intl.DateTimeFormat('en');让 a = f.formatToParts();控制台.log(a); } { // 示例 2 let f = new Intl.DateTimeFormat('hi');让 a = f.formatToParts();控制台.log(a); }

最好将格式数组映射到结果字符串:

函数加入(t,a,s){函数格式(m){让f=新Intl.DateTimeFormat('en',m);返回 f.format(t); } return a.map(format).join(s); } let a = [{day: 'numeric'}, {month: 'short'}, {year: 'numeric'}];让 s = join(new Date, a, '-');控制台.log(s);

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

让 d = new Date(2010, 7, 5);让 ye = new Intl.DateTimeFormat('en', { year: 'numeric' }).format(d);让 mo = new Intl.DateTimeFormat('en', { month: 'short' }).format(d); let da = new Intl.DateTimeFormat('en', { day: '2-digit' }).format(d); console.log(`${da}-${mo}-${ye}`);

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

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


或者扩展 Date 对象,就像我在 stackoverflow.com/questions/3187790/… 中所做的那样
我知道 ye 是年,mo 是月,da 是日。 o 是什么? a 是什么? m 是什么?你能使用正确的变量名吗?
在 2021 年,momentjs 文档说我们希望阻止 Moment 被用于未来的新项目
这是最好的答案恕我直言(最后一个片段),因为允许任何格式的灵活性,即您不需要寻找满足您需求的国家代码
l
lorem monkey

如果您需要使用纯 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

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

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

您还可以使用 .toString().padStart(2, '0') 填充零
@BennyJobigan 应该提到的是,String.padStart() 仅适用于 ECMAScript 2017。
S
Stephan Muller

使用 date.format library

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

返回:

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

dateformat on npm

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


他的“L”代码是错误的,他应该删除“L > 99?”部分...除此之外,它非常整洁,如果不是太好本地化的话。
此解决方案也可作为 npm 包提供:npmjs.com/package/dateformat
如果您要麻烦导入外部依赖项,我建议您使用 moment.js。它可以进行这种类型的日期格式化:momentjs.com/docs/#/displaying 而且它有更多的功能。
与 IE 中的 Date API 相比,时区也适用于日期格式
T
Teocci

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

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

请记住,上述解决方案并未考虑您的时区偏移。

您可以考虑改用这个函数:

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

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

var date = new Date();函数 toLocal(date) { var local = new Date(date); local.setMinutes(date.getMinutes() - date.getTimezoneOffset());返回 local.toJSON(); } function toJSONLocal(date) { var local = new Date(date); local.setMinutes(date.getMinutes() - date.getTimezoneOffset());返回 local.toJSON().slice(0, 10); } // 检查你的开发工具控制台 console.log(date.toJSON()); console.log(date.toISOString()); console.log(toLocal(date)); console.log(toJSONLocal(date));

Date.toISOString

日期.toJSON

字符串切片

外部示例


您可以执行 new Date(date + " UTC") 来欺骗时区,并且可以消除 setMinutes 行。伙计,javascript很脏
Y10K 兼容版本:var today = new Date().toISOString().slice(0,-14) :)
或者像这样new Date().toISOString().split('T')[0]
new Date().toISOString().slice(0, 16).replace('T',' ') 包括时间
只是评论说缺少时区并不是“一天开始/结束时”的一些小不便。例如,在澳大利亚,直到上午 11 点左右,日期可能是错误的——将近半天!
i
ino

自定义格式化功能:

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

函数 dateToYMD(date) { var d = date.getDate(); var m = date.getMonth() + 1; //月份从 0 到 11 var y = date.getFullYear();返回 '' + y + '-' + (m<=9 ? '0' + m : m) + '-' + (d <= 9 ? '0' + d : d); } console.log(dateToYMD(new Date(2017,10,5))); // 11 月 5 日

OP 格式可以生成如下:

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

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

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

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

标准 ECMAScript 格式化函数:

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

toDateString:依赖于实现,只显示日期。 https://262.ecma-international.org/#sec-date.prototype.todatestring new Date().toDateString(); // 例如“2016 年 11 月 11 日星期五”

toISOString:显示 ISO 8601 日期和时间。 https://262.ecma-international.org/#sec-date.prototype.toisostring new Date().toISOString(); // 例如“2016-11-21T08:00:00.000Z”

toJSON:JSON 的字符串化符。 https://262.ecma-international.org/#sec-date.prototype.tojson new Date().toJSON(); // 例如“2016-11-21T08:00:00.000Z”

toLocaleDateString:依赖于实现,区域设置格式的日期。 https://262.ecma-international.org/#sec-date.prototype.tolocaledatestring new Date().toLocaleDateString(); // 例如“21/11/2016”

toLocaleString:依赖于实现,区域设置格式的日期和时间。 https://262.ecma-international.org/#sec-date.prototype.tolocalestring new Date().toLocaleString(); // 例如“21/11/2016, 08:00:00 AM”

toLocaleTimeString:依赖于实现,采用区域设置格式的时间。 https://262.ecma-international.org/#sec-date.prototype.tolocaletimestring new Date().toLocaleTimeString(); // 例如“08:00:00 AM”

toString:日期的通用 toString。 https://262.ecma-international.org/#sec-date.prototype.tostring new Date().toString(); // 例如“2016 年 11 月 21 日星期五 08:00:00 GMT+0100(西欧标准时间)”

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

新的 Date().toISOString().slice(0,10); //返回 YYYY-MM-DD

示例片段:

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

指定标准函数的语言环境:

上面列出的一些标准函数取决于语言环境:

toLocaleDateString()

toLocaleTimeString()

toLocalString()

这是因为不同的文化使用不同的格式,并以不同的方式表达他们的日期或时间。默认情况下,该函数将返回在其运行的设备上配置的格式,但这可以通过设置参数 (ECMA-402) 来指定。

toLocaleDateString([locales[, options]])
toLocaleTimeString([locales[, options]])
toLocaleString([locales[, options]])
//e.g. toLocaleDateString('ko-KR');

option 第二个参数,允许在所选语言环境中配置更具体的格式。例如,月份可以显示为全文或缩写。

toLocaleString('en-GB', { month: 'short' })
toLocaleString('en-GB', { month: 'long' })

示例片段:

console.log("1) "+ new Date().toLocaleString('en-US')); console.log("2) "+ new Date().toLocaleString('ko-KR')); console.log("3) "+ new Date().toLocaleString('de-CH')); console.log("4) "+ new Date().toLocaleString('en-GB', { hour12: false })); console.log("5) "+ new Date().toLocaleString('en-GB', { hour12: true }));

关于语言环境的一些良好做法:

大多数人不喜欢他们的日期以外国人格式出现,因此,尽可能保留默认语言环境(在任何地方设置“en-US”)。

实现从/到 UTC 的转换可能具有挑战性(考虑 DST、时区不是 1 小时的倍数等)。尽可能使用经过良好测试的库。

不要假设区域设置与一个国家/地区相关:几个国家/地区有很多(加拿大、印度等)

避免通过非标准方式检测语言环境。在这里您可以了解多个陷阱:检测键盘布局、通过地理位置检测语言环境等。


我认为英国示例的语言环境应该是“en-GB”以获得“dd/mm/yyyy”格式
我解决了这个问题。谢谢
很好地列出了 Intl.DateTimeFormat() constructor 支持的参数如下:developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/…
感谢您从不使用“ECMA vodoo”的示例开始
.toJSON() 在底层使用 .toIsoString()(根据 docs)。 需要注意 ISO 转换会转换为另一个时区,这可能会更改日期部分(请参阅其他评论)。此外,似乎OP想要转换为Oracle(等)“语言环境/文化”,而不是人类......
D
Dmitry Pavlov

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

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

// formatted will be 'Jul 8, 2014'

一些日期选择器日期格式选项可用here


g
glenatron

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

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

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

参考:

本地化格式

时间

编辑添加:toLocaleFormat 现在已被弃用,如上面的链接所示。


toLocaleFormat() 似乎只适用于 Firefox。 IE 和 Chrome 对我来说都失败了。
Chrome 有 .toLocaleString('en') 方法。似乎新浏览器支持此 developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/…
new Intl.DateTimeFormat 似乎是替换 developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/…
年后,此功能在其他浏览器中仍然无法使用,并且在 Firefox 中已被弃用Deprecated_toLocaleFormat
P
Peter Mortensen

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

另一方面,如果您需要更多日期信息,MomentJS 是一个很好的解决方案。

例如:

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

重要的是:除非您知道 YYYYyyyy 之间的区别,否则不要使用 YYYYstackoverflow.com/questions/15133549/…
@Domin 特定于 iOS 中的 NSDateFormatter,例如在 Objective-C 或 Swift 中使用。这个问题是关于浏览器中的 Javascript,这个答案使用 MomentJS,其中 YYYY(不是 yyyy)是标准年份,GGGG(不是 YYYY)是基于 ISO 周的年份。
J
John Slegers

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

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

今天执行的输出(2016 年 1 月 24 日):

'24-Jan-2016'

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


J
JD Smith

一行中的请求格式 - 没有库也没有 Date 方法,只有正则表达式:

var d = (new Date()).toString().replace(/\S+\s(\S+)\s(\d+)\s(\d+)\s.*/,'$2-$1-$3');
// date will be formatted as "14-Oct-2015" (pass any date object in place of 'new Date()')

在我的测试中,这在主要浏览器(Chrome、Safari、Firefox 和 IE)中可靠地工作。正如@RobG 指出的那样, Date.prototype.toString() 的输出依赖于实现,因此对于国际或非浏览器实现,只需测试输出以确保它在您的 JavaScript 引擎中正常工作。您甚至可以添加一些代码来测试字符串输出,并在进行正则表达式替换之前确保它与您期望的匹配。


h
hakre

@Sébastien——替代所有浏览器支持

new Date(parseInt(496407600)*1000).toLocaleDateString('de-DE', {
year: 'numeric',
month: '2-digit',
day: '2-digit'
}).replace(/\./g, '/');

文档:https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date/toLocaleDateString

基于 Date.toLocaleDateString 的高阶标记模板文字示例:

const date = new Date(Date.UTC(2020, 4, 2, 3, 23, 16, 738));
const fmt = (dt, lc = "en-US") => (str, ...expr) =>
    str.map((str, i) => str + (expr[i]?dt.toLocaleDateString(lc, expr[i]) :'')).join('')

console.log(fmt(date)`${{year: 'numeric'}}-${{month: '2-digit'}}-${{day: '2-digit'}}`);
// expected output: "2020-05-02"

您可以简单地使用“en-GB”作为语言环境,而不是执行 .replace()。 :)
l
lewdev

打包解决方案: Luxondate-fns

如果您想使用一种解决方案来适应所有人,我建议使用 date-fns 或 Luxon。

Luxon 托管在 Moment.js 网站上,由 Moment.js 开发人员开发,因为 Moment.js 存在开发人员想要解决但无法解决的限制。

安装:

npm install luxonyarn add luxon(其他安装方法请访问链接)

例子:

luxon.DateTime.fromISO('2010-08-10').toFormat('yyyy-LLL-dd');

产量:

2010 年 8 月 10 日

手动解决方案

使用与 Moment.js、Class DateTimeFormatter (Java)Class SimpleDateFormat (Java) 类似的格式,我实现了一个全面的解决方案 formatDate(date, patternStr),其中的代码易于阅读和修改。您可以显示日期、时间、上午/下午等。有关更多示例,请参见代码。

例子:

formatDate(new Date(), 'EEEE, MMMM d, yyyy HH:mm:ss:S')

formatDate 在下面的代码段中实现)

产量:

2018 年 10 月 12 日星期五 18:11:23:445

通过单击“运行代码片段”来试用代码。

日期和时间模式

yy = 2 位数年份; yyyy = 全年

M = 数字月份; MM = 2 位数的月份; MMM = 短月份名称; MMMM = 完整的月份名称

EEEE = 完整的工作日名称; EEE = 简短的工作日名称

d = 数字日; dd = 2 位数的日期

h = 上午/下午小时; hh = 2 位数的上午/下午时间; H = 小时; HH = 2 位数小时

m = 分钟; mm = 2 位数分钟; aaa = 上午/下午

s = 秒; ss = 2 位数秒

S = 毫秒

var monthNames = [“一月”、“二月”、“三月”、“四月”、“五月”、“六月”、“七月”、“八月”、“九月”、“十月”、“十一月”、“十二月” " ]; var dayOfWeekNames = [“星期日”、“星期一”、“星期二”、“星期三”、“星期四”、“星期五”、“星期六”];函数 formatDate(date, patternStr){ if (!patternStr) { patternStr = 'M/d/yyyy'; } var day = date.getDate(), month = date.getMonth(), year = date.getFullYear(), hour = date.getHours(), minute = date.getMinutes(), second = date.getSeconds(),毫秒 = date.getMilliseconds(), h = 小时 % 12, hh = twoDigitPad(h), HH = twoDigitPad(hour), mm = twoDigitPad(minute), ss = twoDigitPad(second), aaa = hour < 12 ? 'AM' : 'PM', EEEE = dayOfWeekNames[date.getDay()], EEE = EEEE.substr(0, 3), dd = twoDigitPad(day), M = month + 1, MM = twoDigitPad(M), MMMM = 月名[月], MMM = MMMM.substr(0, 3), yyyy = 年 + "", yy = yyyy.substr(2, 2) ; // 检查是否会使用月份名称 patternStr = patternStr .replace('hh', hh).replace('h', h) .replace('HH', HH).replace('H', hour) .replace('mm', mm).replace('m', minute) .replace('ss', ss).replace('s', second) .replace('S', 毫秒) .replace('dd ', dd).replace('d', day) .replace('EEEE', EEEE).replace('EEE', EEE) .replace('yyyy', yyyy) .replace('yy', yy) 。替换('aaa',aaa); if (patternStr.indexOf('MMM') > -1) { patternStr = patternStr .replace('MMMM', MMMM) .replace('MMM', MMM); } else { patternStr = patternStr .replace('MM', MM) .replace('M', M); } 返回模式Str; } function twoDigitPad(num) { return num < 10 ? “0”+数字:数字; } console.log(formatDate(new Date())); console.log(formatDate(new Date(), 'dd-MMM-yyyy')); //OP的请求console.log(formatDate(new Date(), 'EEEE, MMMM d, yyyy HH:mm:ss.S aaa')); console.log(formatDate(new Date(), 'EEE, MMM d, yyyy HH:mm')); console.log(formatDate(new Date(), 'yyyy-MM-dd HH:mm:ss.S')); console.log(formatDate(new Date(), 'M/dd/yyyy h:mmaaa'));

感谢@Gerry 提出 Luxon。


是的。 Moment 已被弃用。请使用 luxon
r
robsiemb

好的,我们有一个叫做 Intl 的东西,它对于在 JavaScript 中格式化日期非常有用:

您的日期如下:

var date = '10/8/2010';

然后使用 new Date() 更改为 Date ,如下所示:

date = new Date(date);

现在您可以使用如下所示的语言环境列表以任何您喜欢的方式对其进行格式化:

date = new Intl.DateTimeFormat('en-AU').format(date); // Australian date format: "8/10/2010" 

date = new Intl.DateTimeFormat('en-US').format(date); // USA date format: "10/8/2010" 

date = new Intl.DateTimeFormat('ar-EG').format(date);  // Arabic date format: "٨‏/١٠‏/٢٠١٠"

如果您确实想要上面提到的格式,您可以执行以下操作:

date = new Date(Date.UTC(2010, 7, 10, 0, 0, 0));
var options = {year: "numeric", month: "short", day: "numeric"};
date = new Intl.DateTimeFormat("en-AU", options).format(date).replace(/\s/g, '-');

结果将是:

"10-Aug-2010"

有关详细信息,请参阅 Intl APIIntl.DateTimeFormat 文档。


IE 不支持
它只是在 IE11 之前,IE10- 在这之前已经过时了,所以这是可以理解的。 92% 来自 caniuse,非常好caniuse.com/#search=datetimeformat
v
vdegenne

使用 ECMAScript Edition 6 (ES6/ES2015) 字符串模板:

let d = new Date();
let formatted = `${d.getFullYear()}-${d.getMonth() + 1}-${d.getDate()}`;

如果您需要更改分隔符:

const delimiter = '/';
let formatted = [d.getFullYear(), d.getMonth() + 1, d.getDate()].join(delimiter);

p
perepm

Date 构造函数(和 Date.parse())在构造日期时仅接受一种格式作为参数,即 ISO 8601

// new Date('YYYY-MM-DDTHH:mm:ss.sssZ')
const date = new Date('2017-08-15')

但是由于浏览器的差异和不一致,强烈建议不要从字符串中解析 a(MDN 建议不要使用日期字符串创建日期)。

推荐的替代方法是直接从数字数据构建您的 Date 实例,如下所示:

new Date(2017, 7, 15) // Month is zero-indexed

那就是解析。现在,要将您的日期格式化为您想要的字符串,您有几个选项是 Date 对象的本机选项(尽管我相信没有一个符合您需要的格式):

date.toString()       // 'Wed Jan 23 2019 17:23:42 GMT+0800 (Singapore Standard Time)'
date.toDateString()   // 'Wed Jan 23 2019'
date.toLocaleString() // '23/01/2019, 17:23:42'
date.toGMTString()    // 'Wed, 23 Jan 2019 09:23:42 GMT'
date.toUTCString()    // 'Wed, 23 Jan 2019 09:23:42 GMT'
date.toISOString()    // '2019-01-23T09:23:42.079Z'

对于其他格式选项,恐怕您将不得不求助于 Moment.jsday.js 等库。

将日期格式提示从 this article 归功于 Zell Liew


j
jmiraglia

这是我刚刚编写的一些代码,用于处理我正在处理的项目的日期格式。它模仿 PHP 日期格式化功能来满足我的需要。随意使用它,它只是扩展已经存在的 Date() 对象。这可能不是最优雅的解决方案,但它可以满足我的需求。

var d = new Date(); 
d_string = d.format("m/d/Y h:i:s");

/**************************************
 * Date class extension
 * 
 */
    // Provide month names
    Date.prototype.getMonthName = function(){
        var month_names = [
                            'January',
                            'February',
                            'March',
                            'April',
                            'May',
                            'June',
                            'July',
                            'August',
                            'September',
                            'October',
                            'November',
                            'December'
                        ];

        return month_names[this.getMonth()];
    }

    // Provide month abbreviation
    Date.prototype.getMonthAbbr = function(){
        var month_abbrs = [
                            'Jan',
                            'Feb',
                            'Mar',
                            'Apr',
                            'May',
                            'Jun',
                            'Jul',
                            'Aug',
                            'Sep',
                            'Oct',
                            'Nov',
                            'Dec'
                        ];

        return month_abbrs[this.getMonth()];
    }

    // Provide full day of week name
    Date.prototype.getDayFull = function(){
        var days_full = [
                            'Sunday',
                            'Monday',
                            'Tuesday',
                            'Wednesday',
                            'Thursday',
                            'Friday',
                            'Saturday'
                        ];
        return days_full[this.getDay()];
    };

    // Provide full day of week name
    Date.prototype.getDayAbbr = function(){
        var days_abbr = [
                            'Sun',
                            'Mon',
                            'Tue',
                            'Wed',
                            'Thur',
                            'Fri',
                            'Sat'
                        ];
        return days_abbr[this.getDay()];
    };

    // Provide the day of year 1-365
    Date.prototype.getDayOfYear = function() {
        var onejan = new Date(this.getFullYear(),0,1);
        return Math.ceil((this - onejan) / 86400000);
    };

    // Provide the day suffix (st,nd,rd,th)
    Date.prototype.getDaySuffix = function() {
        var d = this.getDate();
        var sfx = ["th","st","nd","rd"];
        var val = d%100;

        return (sfx[(val-20)%10] || sfx[val] || sfx[0]);
    };

    // Provide Week of Year
    Date.prototype.getWeekOfYear = function() {
        var onejan = new Date(this.getFullYear(),0,1);
        return Math.ceil((((this - onejan) / 86400000) + onejan.getDay()+1)/7);
    } 

    // Provide if it is a leap year or not
    Date.prototype.isLeapYear = function(){
        var yr = this.getFullYear();

        if ((parseInt(yr)%4) == 0){
            if (parseInt(yr)%100 == 0){
                if (parseInt(yr)%400 != 0){
                    return false;
                }
                if (parseInt(yr)%400 == 0){
                    return true;
                }
            }
            if (parseInt(yr)%100 != 0){
                return true;
            }
        }
        if ((parseInt(yr)%4) != 0){
            return false;
        } 
    };

    // Provide Number of Days in a given month
    Date.prototype.getMonthDayCount = function() {
        var month_day_counts = [
                                    31,
                                    this.isLeapYear() ? 29 : 28,
                                    31,
                                    30,
                                    31,
                                    30,
                                    31,
                                    31,
                                    30,
                                    31,
                                    30,
                                    31
                                ];

        return month_day_counts[this.getMonth()];
    } 

    // format provided date into this.format format
    Date.prototype.format = function(dateFormat){
        // break apart format string into array of characters
        dateFormat = dateFormat.split("");

        var date = this.getDate(),
            month = this.getMonth(),
            hours = this.getHours(),
            minutes = this.getMinutes(),
            seconds = this.getSeconds();
        // get all date properties ( based on PHP date object functionality )
        var date_props = {
            d: date < 10 ? '0'+date : date,
            D: this.getDayAbbr(),
            j: this.getDate(),
            l: this.getDayFull(),
            S: this.getDaySuffix(),
            w: this.getDay(),
            z: this.getDayOfYear(),
            W: this.getWeekOfYear(),
            F: this.getMonthName(),
            m: month < 10 ? '0'+(month+1) : month+1,
            M: this.getMonthAbbr(),
            n: month+1,
            t: this.getMonthDayCount(),
            L: this.isLeapYear() ? '1' : '0',
            Y: this.getFullYear(),
            y: this.getFullYear()+''.substring(2,4),
            a: hours > 12 ? 'pm' : 'am',
            A: hours > 12 ? 'PM' : 'AM',
            g: hours % 12 > 0 ? hours % 12 : 12,
            G: hours > 0 ? hours : "12",
            h: hours % 12 > 0 ? hours % 12 : 12,
            H: hours,
            i: minutes < 10 ? '0' + minutes : minutes,
            s: seconds < 10 ? '0' + seconds : seconds           
        };

        // loop through format array of characters and add matching data else add the format character (:,/, etc.)
        var date_string = "";
        for(var i=0;i<dateFormat.length;i++){
            var f = dateFormat[i];
            if(f.match(/[a-zA-Z]/g)){
                date_string += date_props[f] ? date_props[f] : '';
            } else {
                date_string += f;
            }
        }

        return date_string;
    };
/*
 *
 * END - Date class extension
 * 
 ************************************/

G
General Grievance

这可能有助于解决问题:

var d = 新日期(); var options = { day: 'numeric', month: 'long', year: 'numeric' }; console.log(d.toLocaleDateString('en-ZA', options));


I
Iman Bahrampour

在 JavaScript 中格式化 DateTime 的一种有用且灵活的方法是 Intl.DateTimeFormat

var date = new Date();
var options = { year: 'numeric', month: 'short', day: '2-digit'};
var _resultDate = new Intl.DateTimeFormat('en-GB', options).format(date);
// The _resultDate is: "12 Oct 2017"
// Replace all spaces with - and then log it.
console.log(_resultDate.replace(/ /g,'-'));

结果是:"12-Oct-2017"

可以使用 options 参数自定义日期和时间格式。

Intl.DateTimeFormat 对象是启用语言敏感日期和时间格式的对象的构造函数。

句法

new Intl.DateTimeFormat([locales[, options]])
Intl.DateTimeFormat.call(this[, locales[, options]])

参数

语言环境

可选的。带有 BCP 47 语言标记的字符串,或此类字符串的数组。有关 locales 参数的一般形式和解释,请参阅 Intl 页面。允许使用以下 Unicode 扩展键:

nu
Numbering system. Possible values include: "arab", "arabext", "bali", "beng", "deva", "fullwide", "gujr", "guru", "hanidec", "khmr", "knda", "laoo", "latn", "limb", "mlym", "mong", "mymr", "orya", "tamldec", "telu", "thai", "tibt".
ca
Calendar. Possible values include: "buddhist", "chinese", "coptic", "ethioaa", "ethiopic", "gregory", "hebrew", "indian", "islamic", "islamicc", "iso8601", "japanese", "persian", "roc".

选项

可选的。具有以下部分或全部属性的对象:

区域匹配器

要使用的语言环境匹配算法。可能的值为 "lookup""best fit";默认值为 "best fit"。有关此选项的信息,请参阅 Intl 页面。

时区

要使用的时区。唯一必须识别的值实现是 "UTC";默认值是运行时的默认时区。实现还可以识别 IANA 时区数据库的时区名称,例如 "Asia/Shanghai""Asia/Kolkata""America/New_York"

小时12

是否使用 12 小时制(而不是 24 小时制)。可能的值为 truefalse;默认值取决于语言环境。

格式匹配器

要使用的格式匹配算法。可能的值为 "basic""best fit";默认值为 "best fit"。有关使用此属性的信息,请参阅以下段落。

以下属性描述了在格式化输出中使用的日期时间组件及其所需的表示形式。实现需要至少支持以下子集:

weekday, year, month, day, hour, minute, second
weekday, year, month, day
year, month, day
year, month
month, day
hour, minute, second
hour, minute

实现可能支持其他子集,并且将针对所有可用的子集表示组合协商请求以找到最佳匹配。两种算法可用于此协商并由 formatMatcher 属性选择:完全指定的 "basic" 算法和依赖于实现的“最佳拟合”算法。

工作日

工作日的表示。可能的值为 "narrow""short""long"

时代

时代的代表。可能的值为 "narrow""short""long"

年度的代表。可能的值为 "numeric""2-digit"

月份的表示。可能的值为 "numeric""2-digit""narrow""short""long"

当天的代表。可能的值为 "numeric""2-digit"

小时

小时的表示。可能的值为 "numeric""2-digit"

分钟

分钟的表示。可能的值为 "numeric""2-digit"

第二

第二个的代表。可能的值为 "numeric""2-digit"

时区名称

时区名称的表示。可能的值为 "short""long"。每个日期时间组件属性的默认值未定义,但如果所有组件属性未定义,则假定年、月和日为 "numeric"

Check Online

More Details


P
Peter Mortensen

不使用任何外部库的 JavaScript 解决方案:

var now = new Date()
months = ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec']
var formattedDate = now.getDate() + "-" + months[now.getMonth()] + "-" + now.getFullYear()
alert(formattedDate)

K
Kirk Strobeck

new Date().toLocaleDateString() // "3/21/2018"

developer.mozilla.org 上的更多文档


P
Peter Mortensen

我们有很多解决方案,但我认为其中最好的是 Moment.js。所以我个人建议使用 Moment.js 进行日期和时间的操作。

console.log(moment().format('DD-MMM-YYYY'));


C
Carrie Kendall

如果您在代码中使用 jQuery UI,则有一个名为 formatDate() 的内置函数。我用这种方式来格式化今天的日期:

var testdate = Date();
testdate = $.datepicker.formatDate( "d-M-yy",new Date(testdate));
alert(testdate);

您可以看到 many other examples of formatting date in the jQuery UI documentation


A
Amit Kumar Gupta

这就是我为我的 npm 插件实现的方式

var monthNames = [
  "January", "February", "March",
  "April", "May", "June", "July",
  "August", "September", "October",
  "November", "December"
];

var Days = [
  "Sunday", "Monday", "Tuesday", "Wednesday",
  "Thursday", "Friday", "Saturday"
];

var formatDate = function(dt,format){
  format = format.replace('ss', pad(dt.getSeconds(),2));
  format = format.replace('s', dt.getSeconds());
  format = format.replace('dd', pad(dt.getDate(),2));
  format = format.replace('d', dt.getDate());
  format = format.replace('mm', pad(dt.getMinutes(),2));
  format = format.replace('m', dt.getMinutes());
  format = format.replace('MMMM', monthNames[dt.getMonth()]);
  format = format.replace('MMM', monthNames[dt.getMonth()].substring(0,3));
  format = format.replace('MM', pad(dt.getMonth()+1,2));
  format = format.replace(/M(?![ao])/, dt.getMonth()+1);
  format = format.replace('DD', Days[dt.getDay()]);
  format = format.replace(/D(?!e)/, Days[dt.getDay()].substring(0,3));
  format = format.replace('yyyy', dt.getFullYear());
  format = format.replace('YYYY', dt.getFullYear());
  format = format.replace('yy', (dt.getFullYear()+"").substring(2));
  format = format.replace('YY', (dt.getFullYear()+"").substring(2));
  format = format.replace('HH', pad(dt.getHours(),2));
  format = format.replace('H', dt.getHours());
  return format;
}

pad = function(n, width, z) {
  z = z || '0';
  n = n + '';
  return n.length >= width ? n : new Array(width - n.length + 1).join(z) + n;
}

你指的是哪个包?
这有一个错误:首先替换月份名称,然后再替换月份名称。例如,使用此代码 March 将变为 3arch
'M' 的行更改为 format = format.replace("M(?!M)", (dt.getMonth()+1).toString()); 并将其放在 'MMMM' 行的上方
可以在此处找到此示例的演示:jsfiddle.net/Abeeee/Ly8v3s0x/24
M
Melchia

您应该看看 DayJs 它是对 momentJs 的重制,但面向模块化架构非常轻巧。

具有相同现代 API 的 Moment.js 的快速 2kB 替代品

Day.js 是一个极简的 JavaScript 库,它解析、验证、操作和显示现代浏览器的日期和时间,具有很大程度上与 Moment.js 兼容的 API。如果您使用 Moment.js,那么您已经知道如何使用 Day.js。

var date = Date.now(); const formatedDate = dayjs(date).format("YYYY-MM-DD") console.log(formatedDate);


J
Jeffrey Knight
var today = new Date();
var formattedToday = today.toLocaleDateString() + ' ' + today.toLocaleTimeString();

K
Kamil Kiełczewski

受到 JD Smith 奇妙的正则表达式解决方案的启发,我突然有了一个令人头晕目眩的想法:

var D = Date().toString().split(" "); console.log(D[2] + "-" + D[1] + "-" + D[3]);


如果您在 DOM 中需要它,那就是不错的变化!
H
Hinrich

对于任何正在寻找一个非常简单的 ES6 解决方案来复制、粘贴和采用的人:

const dateToString = d => `${d.getFullYear()}-${('00' + (d.getMonth() + 1)).slice(-2)}-${('00' + d. getDate()).slice(-2)}` // 如何使用: const myDate = new Date(Date.parse('04 Dec 1995 00:12:00 GMT')) console.log(dateToString(myDate)) // 1995-12-04


小改进:为了确保两位数的结果,这工作正常:('0' + oneOrTwoDigitNumber).slice(-2)。无需使用 ('00' + oneOrTwoDigitNumber).slice(-2),因为我们知道 oneOrTwoDigitNumber 的长度至少为一位。
K
K Vij

截至 2019 年,您似乎可以让 toLocaleDateString 仅返回某些部分,然后您可以根据需要加入它们:

var date = new Date();

console.log(date.toLocaleDateString("en-US", { day: 'numeric' }) 
            + "-"+ date.toLocaleDateString("en-US", { month: 'short' })
            + "-" + date.toLocaleDateString("en-US", { year: 'numeric' }) );

> 16-Nov-2019

console.log(date.toLocaleDateString("en-US", { month: 'long' }) 
            + " " + date.toLocaleDateString("en-US", { day: 'numeric' }) 
            + ", " + date.toLocaleDateString("en-US", { year: 'numeric' }) );

> November 16, 2019

P
Peter Mortensen

它在 Internet Explorer 11、Firefox 和 Chrome 中的工作方式相同(Chrome 80.x 在选择 en-UK 时显示 12 小时格式)。

const d = new Date('2010/08/05 23:45') // 26.3.2020 const dtfUK = new Intl.DateTimeFormat('UK', { year: 'numeric', month: '2-digit', day :'2-digit',小时:'2-digit',分钟:'2-digit',秒:'2-digit' }); // const dtfUS = new Intl.DateTimeFormat('en', { year: 'numeric', month: '2-digit', day: '2-digit', hour: '2-digit',minute: '2-数字',第二个:'2-digit' }); // console.log(dtfUS.format(d)); // 2010 年 8 月 5 日晚上 11:45:00 console.log(dtfUK.format(d)); // 05.08.2010 23:45:00 /* node.js: 08/05/2010, 11:45:00 PM 2010-08-05 23:45:00 */

更一般的东西呢?

var d = new Date('2010-08-10T10:34:56.789Z'); var str = d.toDateString() + // 2010 年 8 月 10 日星期二 ' ' + d.toTimeString().split(' ')[0] + // 12:34:56, GMT+0x00 (GMT+0x:00 ) ' ' + (d.getMonth() + 101) + // 108 ' ' + d.getMilliseconds(); // 789 控制台.log(str); // 2010 年 8 月 10 日星期二 12:34:56 108 789 console.log(// $1 星期二 $2 Aug $3 11 $4 2020 $5 12 $6 34 $7 56 $8 108 $9 789 str.replace(/(\S{3}) ( \S{3}) (\d{1,2}) (\d{4}) (\d{2}):(\d{2}):(\d{2}) 1(\d{ 2}) (\d{1,3})/, '$3-$2-$4 $5:$6.$9 ($1)') ); // 2010 年 8 月 10 日 12:34.789 (Tue) /* $1: Tue Week Day string $2: Aug Month short text $3: 11 Day $4: 2010 Year $5: 12 Hour $6: 34 Minute $7: 56 Seconds $8: 08月 $9:789 毫秒 */

或者例如 1 行 IIFE “库” ;-)

console.log( (function (frm, d) { return [d.toDateString(), d.toTimeString().split(' ')[0], (d.getMonth() + 101), d.getMilliseconds() ].join(' ').replace(/(\S{3}) (\S{3}) (\d{1,2}) (\d{4}) (\d{2}):( \d{2}):(\d{2}) 1(\d{2}) (\d{1,3})/, frm); }) ('$4/$8/$3 $5:$6 ($1 )', 新日期()) );

如果您不需要它们,您可以删除无用的部分和/或更改索引。