如果您需要比当前接受的答案更少的格式控制,可以使用Date#toLocaleDateString
来创建标准的区域设置特定渲染。 locale
和options
参数允许应用程序指定应使用其格式约定的语言,并允许对呈现进行一些自定义。
所有这些键都是可选的。您可以根据自己的需求更改选项值的数量,这也将反映每个日期时间术语的存在。
注意:如果您只想配置内容选项,但仍要使用当前区域设置,则将第一个参数传递为null
将导致错误。请改用undefined
。
您可以使用更多语言选项。
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
您也可以使用 toLocaleString()
方法来实现相同的目的。唯一的区别是,当您不传递任何选项时,此函数提供时间信息。
// Example
9/17/2016, 1:21:34 PM
date.toLocaleDateString("en-US", { day: 'numeric' }) + "-"+ date.toLocaleDateString("en-US", { month: 'short' }) + "-" + date.toLocaleDateString("en-US", { year: 'numeric' })
应该会得到16-Nov-2019
。 - K VijDateTimeFormat
对象(它是ECMAScript国际化API的一部分)中提取日期(或时间)组件,然后手动创建一个带有所需分隔符的字符串。DateTimeFormat#formatToParts
。您可以解构数组,但这并不理想,因为数组输出取决于区域设置。
{ // example 1
let formatter = new Intl.DateTimeFormat('en');
let example = formatter.formatToParts();
console.log(example);
}
{ // example 2
let formatter = new Intl.DateTimeFormat('hi');
let example = formatter.formatToParts();
console.log(example);
}
function join(date, options, separator) {
function format(option) {
let formatter = new Intl.DateTimeFormat('en', option);
return formatter.format(date);
}
return options.map(format).join(separator);
}
let options = [{day: 'numeric'}, {month: 'short'}, {year: 'numeric'}];
let joined = join(new Date, options, '-');
console.log(joined);
DateTimeFormat#format
逐个提取DateTimeFormat
的部分,但请注意,截至2020年3月,ECMAScript实现中存在一个关于分钟和秒钟前导零的bug(这个问题可以通过上述方法绕过)。
let date = new Date(2010, 7, 5);
let year = new Intl.DateTimeFormat('en', { year: 'numeric' }).format(date);
let month = new Intl.DateTimeFormat('en', { month: 'short' }).format(date);
let day = new Intl.DateTimeFormat('en', { day: '2-digit' }).format(date);
console.log(`${day}-${month}-${year}`);
Date
对象,就像我在https://dev59.com/l07Sa4cB1Zd3GeqP7eJ2#3189792中所做的那样。 - Marcel Korpelye
代表年,mo
代表月,da
代表日。那么o
代表什么?a
又代表什么?m
又是什么呢?请使用适当的变量命名。 - mikemaccana如果您需要使用纯JavaScript快速格式化日期,请使用getDate
,getMonth + 1
,getFullYear
,getHours
和getMinutes
:
var d = new Date();
var datestring = d.getDate() + "-" + (d.getMonth()+1) + "-" + d.getFullYear() + " " +
d.getHours() + ":" + d.getMinutes();
// 16-5-2015 9:50
或者,如果你需要在前面加上0:
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')
来补足零位。 - Benny JobiganString.padStart()
只能在 ECMAScript 2017 中使用。 - JHHlet pad = v => `0${v}`.slice(-2);
,可以将填充版本简化为:let datestring = `${d.getFullYear()}-${pad(d.getMonth() + 1)}-${pad(d.getDate())}_${pad(d.getHours())}-${pad(d.getMinutes())}`;
。 - klues使用date.format库:
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
我想要将今天的日期转换为一个像2012-06-23
这样的适用于MySQL的日期字符串,并将该字符串用作我的查询参数之一。我找到的简单解决方案是:
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();
function toLocal(date) {
var local = new Date(date);
local.setMinutes(date.getMinutes() - date.getTimezoneOffset());
return local.toJSON();
}
function toJSONLocal(date) {
var local = new Date(date);
local.setMinutes(date.getMinutes() - date.getTimezoneOffset());
return local.toJSON().slice(0, 10);
}
// check out your devtools console
console.log(date.toJSON());
console.log(date.toISOString());
console.log(toLocal(date));
console.log(toJSONLocal(date));
new Date(date + " UTC")
来欺骗时区,同时可以省略掉setMinutes
这一行代码。哎呀,JavaScript 真是有点混乱。 - Vajk Hermeczvar today = new Date().toISOString().slice(0,-14)
:) (翻译:这是一段JavaScript代码,用于获取当前日期并将其格式化为ISO标准格式。它会将日期转换为字符串,并去掉最后14个字符以去除时间信息。Y10K兼容表示该代码可以处理距今10000年后的日期。笑脸表情是作者在文本末尾加入的一个积极的符号。) - Alex Shaffernew Date().toISOString().split('T')[0]
- rofrolnew Date().toISOString().slice(0, 19).replace('T',' ')
可以包含时间信息。 - Gerrie van Wyk对于固定格式,可以使用一个简单的函数来完成任务。以下示例生成国际格式 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
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
注意:然而,通常不推荐扩展JavaScript标准库(例如将此函数添加到Date原型中)。
更高级的函数可以根据格式参数生成可配置的输出。
如果编写格式化函数太长了,有很多库可以完成它。其他答案已经列举了一些。但增加依赖也有其代价。
自ECMAScript的较新版本以来,Date
类具有一些特定的格式化函数:
toDateString: Implementation dependent, show only the date.
https://262.ecma-international.org/#sec-date.prototype.todatestring
new Date().toDateString(); // e.g. "Fri Nov 11 2016"
toISOString: Show ISO 8601 date and time.
https://262.ecma-international.org/#sec-date.prototype.toisostring
new Date().toISOString(); // e.g. "2016-11-21T08:00:00.000Z"
toJSON: Stringifier for JSON.
https://262.ecma-international.org/#sec-date.prototype.tojson
new Date().toJSON(); // e.g. "2016-11-21T08:00:00.000Z"
toLocaleDateString: Implementation dependent, a date in locale format.
https://262.ecma-international.org/#sec-date.prototype.tolocaledatestring
new Date().toLocaleDateString(); // e.g. "21/11/2016"
toLocaleString: Implementation dependent, a date&time in locale format.
https://262.ecma-international.org/#sec-date.prototype.tolocalestring
new Date().toLocaleString(); // e.g. "21/11/2016, 08:00:00 AM"
toLocaleTimeString: Implementation dependent, a time in locale format.
https://262.ecma-international.org/#sec-date.prototype.tolocaletimestring
new Date().toLocaleTimeString(); // e.g. "08:00:00 AM"
toString: Generic toString for Date.
https://262.ecma-international.org/#sec-date.prototype.tostring
new Date().toString(); // e.g. "Fri Nov 21 2016 08:00:00 GMT+0100 (W. Europe Standard Time)"
注:可以通过这些格式化生成自定义输出。
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));
上述某些标准函数依赖于语言环境:
toLocaleDateString()
toLocaleTimeString()
toLocalString()
这是因为不同的文化会使用不同的格式,并以不同的方式表达其日期或时间。 该函数默认返回设备所配置的格式,但可以通过设置参数(ECMA-402)来指定其格式。
toLocaleDateString([locales[, options]])
toLocaleTimeString([locales[, options]])
toLocaleString([locales[, options]])
//e.g. toLocaleDateString('ko-KR');
选项
的第二个参数允许在所选语言环境中配置更具体的格式。例如,月份可以显示为全文本或缩写形式。toLocaleString('en-GB', { month: 'short' })
toLocaleString('en-GB', { month: 'long' })
Examples snippets:
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 }));
关于本地化的一些良好实践:
Intl.DateTimeFormat() 构造函数
支持的参数在此链接中列出:https://developer.mozilla.org/zh-CN/docs/Web/JavaScript/Reference/Global_Objects/Intl/DateTimeFormat/DateTimeFormat。 - ino.toJSON()
在内部使用.toISOString()
方法 (根据文档)。需要注意的是,ISO转换会转换为另一个时区,这可能会更改日期部分(请参见其他评论)。此外,似乎OP想要将其转换为Oracle(等)的“区域设置/文化”,而不是人类文化... - frIT如果您已经在项目中使用jQuery UI,您可以这样做:
var formatted = $.datepicker.formatDate("M d, yy", new Date("2014-07-08T09:02:21.377"));
// formatted will be 'Jul 8, 2014'
这里提供了一些可供使用的日期选择器日期格式选项,请点击此处查看。
toLocaleFormat
早已被弃用,自 Firefox 版本58起已被移除。请参见toLocaleFormat
我认为你可以直接使用非标准的 Date 方法 toLocaleFormat(formatString)
formatString:格式字符串应符合C语言中strftime()
函数所期望的相同格式。
var today = new Date();
today.toLocaleFormat('%d-%b-%Y'); // 30-Dec-2011
参考资料:
对于小的一次性任务,纯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
YYYY
和 yyyy
之间的差别,否则请勿使用 YYYY
。请注意:若不了解 YYYY
和 yyyy
的区别,请勿使用 YYYY
。 - DominYYYY
(而不是yyyy
)是标准年份,GGGG
(而不是YYYY
)是基于ISO的周年份。 - Mark Reed
myDate.getDay()
并不返回一周中的星期几,而是返回星期几在这周中的位置。myDate.getDate()
返回的是当前日期的星期几。 - JimenemextoLocaleDateString
。 - onmyway133