在 JavaScript 中,如何格式化日期对象以打印为10-Aug-2010
?
59 回答
如果您需要对格式的控制比当前接受的答案略少,Date#toLocaleDateString
可用于创建标准的特定于语言环境的渲染。和参数让应用程序指定应该使用其格式约定的语言,并允许对呈现进行一些自定义locale
。options
选项关键示例:
- 日:一天
的表示。
可能的值为“数字”、“2 位”。 - weekday:
表示工作日。
可能的值是“窄”、“短”、“长”。 - 年份:年份
的表示。
可能的值为“数字”、“2 位”。 - 月:月份
的表示。
可能的值是“numeric”、“2-digit”、“narrow”、“short”、“long”。 - 小时:
小时的表示。
可能的值为“数字”、“2 位”。 - 分钟:分钟
的表示。
可能的值为“数字”、“2 位”。 - second:第二个
的表示。
可能的值为“数字”、2 位数字。
所有这些键都是可选的。您可以根据您的要求更改选项值的数量,这也将反映每个日期时间项的存在。
注意:如果您只想配置内容选项,但仍使用当前语言环境,则传递null
第一个参数将导致错误。改为使用undefined
。
对于不同的语言:
- “en-US”:英语
- “hi-IN”:印地语
- “ja-JP”:日语
您可以使用更多语言选项。
例如
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
参考:
对于自定义分隔的日期格式,您必须从DateTimeFormat
对象(这是
ECMAScript 国际化 API的一部分)中提取日期(或时间)组件,然后手动创建带有所需分隔符的字符串。
为此,您可以使用DateTimeFormat#formatToParts
. 您可以解构数组,但这并不理想,因为数组输出取决于语言环境:
{ // example 1
let f = new Intl.DateTimeFormat('en');
let a = f.formatToParts();
console.log(a);
}
{ // example 2
let f = new Intl.DateTimeFormat('hi');
let a = f.formatToParts();
console.log(a);
}
最好将格式数组映射到结果字符串:
function join(t, a, s) {
function format(m) {
let f = new Intl.DateTimeFormat('en', m);
return f.format(t);
}
return a.map(format).join(s);
}
let a = [{day: 'numeric'}, {month: 'short'}, {year: 'numeric'}];
let s = join(new Date, a, '-');
console.log(s);
DateTimeFormat
您也可以使用 逐一
拉出部分DateTimeFormat#format
,但请注意,使用此方法时,截至 2020 年 3 月,ECMAScript 实现中存在一个错误,即分钟和秒的前导零(此错误被上述方法规避)。
let d = new Date(2010, 7, 5);
let ye = new Intl.DateTimeFormat('en', { year: 'numeric' }).format(d);
let 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.js、luxon),因为该领域隐藏着许多复杂性。
请注意, IE10不支持上述解决方案中使用的 ECMAScript 国际化 API (2020 年 2 月全球浏览器市场份额为0.03% )。
如果您需要使用纯 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
或者,如果您需要用零填充它:
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
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
好吧,我想要的是将今天的日期转换为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();
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));
自定义格式化功能:
对于固定格式,一个简单的功能就可以完成。以下示例生成国际格式 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 格式化函数:
由于 ECMAScript 的更新版本,Date
该类具有一些特定的格式化功能:
toDateString:依赖于实现,仅显示日期。
https://262.ecma-international.org/#sec-date.prototype.todatestring
new Date().toDateString(); // e.g. "Fri Nov 11 2016"
toISOString:显示 ISO 8601 日期和时间。
https://262.ecma-international.org/#sec-date.prototype.toisostring
new Date().toISOString(); // e.g. "2016-11-21T08:00:00.000Z"
toJSON:JSON 的字符串化符。
https://262.ecma-international.org/#sec-date.prototype.tojson
new Date().toJSON(); // e.g. "2016-11-21T08:00:00.000Z"
toLocaleDateString:依赖于实现,区域设置格式的日期。
https://262.ecma-international.org/#sec-date.prototype.tolocaledatestring
new Date().toLocaleDateString(); // e.g. "21/11/2016"
toLocaleString:依赖于实现,以语言环境格式表示的日期和时间。
https://262.ecma-international.org/#sec-date.prototype.tolocalestring
new Date().toLocaleString(); // e.g. "21/11/2016, 08:00:00 AM"
toLocaleTimeString:依赖于实现,以语言环境格式表示的时间。
https://262.ecma-international.org/#sec-date.prototype.tolocaletimestring
new Date().toLocaleTimeString(); // e.g. "08:00:00 AM"
toString:日期的通用 toString。
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
示例片段:
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');
第二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 小时的倍数等)。尽可能使用经过良好测试的库。
- 不要假设区域设置与一个国家/地区相关:几个国家/地区有很多(加拿大、印度等)
- 避免通过非标准方式检测语言环境。在这里您可以了解多个陷阱:检测键盘布局、通过地理位置检测语言环境等。
如果你已经在你的项目中使用 jQuery UI,你可以这样做:
var formatted = $.datepicker.formatDate("M d, yy", new Date("2014-07-08T09:02:21.377"));
// formatted will be 'Jul 8, 2014'
此处提供了一些可供使用的日期选择器日期格式选项。
我认为您可以使用非标准Date 方法toLocaleFormat(formatString)
formatString:格式字符串,格式与strftime()
C 中的函数所期望的格式相同。
var today = new Date();
today.toLocaleFormat('%d-%b-%Y'); // 30-Dec-2011
参考:
编辑添加:toLocaleFormat
现在已被弃用,如上面的链接所示。
纯 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
在现代浏览器(*)中,您可以这样做:
var today = new Date().toLocaleDateString('en-GB', {
day : 'numeric',
month : 'short',
year : 'numeric'
}).split(' ').join('-');
今天执行的输出(2016 年 1 月 24 日):
'24-Jan-2016'
(*) 根据 MDN,“现代浏览器”是指 Chrome 24+、Firefox 29+、Internet Explorer 11、Edge 12+、Opera 15+ 和 Safari nightly build。
一行中的请求格式 - 没有库也没有 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 引擎中正常工作。您甚至可以添加一些代码来测试字符串输出,并在进行正则表达式替换之前确保它与您期望的匹配。
@Sébastien——替代所有浏览器支持
new Date(parseInt(496407600)*1000).toLocaleDateString('de-DE', {
year: 'numeric',
month: '2-digit',
day: '2-digit'
}).replace(/\./g, '/');
基于 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"
打包解决方案: Luxon
如果您想使用一个解决方案来适应所有人,我强烈建议您使用 Luxon(Moment.js 的现代化版本),它还可以在许多语言环境/语言和大量其他功能中进行格式化。
Luxon 托管在 Moment.js 网站上,由 Moment.js 开发人员开发,因为 Moment.js 存在开发人员想要解决但无法解决的限制。
安装:
npm install luxon
或yarn 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 = [
"January", "February", "March", "April", "May", "June", "July",
"August", "September", "October", "November", "December"
];
var dayOfWeekNames = [
"Sunday", "Monday", "Tuesday",
"Wednesday", "Thursday", "Friday", "Saturday"
];
function 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(),
miliseconds = date.getMilliseconds(),
h = hour % 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 = monthNames[month],
MMM = MMMM.substr(0, 3),
yyyy = year + "",
yy = yyyy.substr(2, 2)
;
// checks to see if month name will be used
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', miliseconds)
.replace('dd', dd).replace('d', day)
.replace('EEEE', EEEE).replace('EEE', EEE)
.replace('yyyy', yyyy)
.replace('yy', yy)
.replace('aaa', aaa);
if (patternStr.indexOf('MMM') > -1) {
patternStr = patternStr
.replace('MMMM', MMMM)
.replace('MMM', MMM);
}
else {
patternStr = patternStr
.replace('MM', MM)
.replace('M', M);
}
return patternStr;
}
function twoDigitPad(num) {
return num < 10 ? "0" + num : num;
}
console.log(formatDate(new Date()));
console.log(formatDate(new Date(), 'dd-MMM-yyyy')); //OP's request
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。
好的,我们有一个叫做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 API和Intl.DateTimeFormat文档。
使用 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);
Date
构造函数 (and )在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'
不使用任何外部库的 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)
这是我刚刚编写的一些代码,用于处理我正在处理的项目的日期格式。它模仿 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
*
************************************/
在 JavaScript 中格式化 DateTimes 的一种有用且灵活的方法是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 小时制)。可能的值为true
和false
; 默认值取决于语言环境。
格式匹配器
要使用的格式匹配算法。可能的值为"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"
。
new Date().toLocaleDateString()
// "3/21/2018"
developer.mozilla.org上的更多文档
我们有很多解决方案,但我认为其中最好的是 Moment.js。所以我个人建议使用 Moment.js 进行日期和时间的操作。
console.log(moment().format('DD-MMM-YYYY'));
<script src="//cdnjs.cloudflare.com/ajax/libs/moment.js/2.14.1/moment.min.js"></script>
如果您在代码中使用 jQuery UI,则有一个名为formatDate()
. 我用这种方式来格式化今天的日期:
var testdate = Date();
testdate = $.datepicker.formatDate( "d-M-yy",new Date(testdate));
alert(testdate);
您可以在 jQuery UI 文档中看到 许多其他格式化日期的示例。
你应该看看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);
<script src="https://cdnjs.cloudflare.com/ajax/libs/dayjs/1.8.16/dayjs.min.js" crossorigin="anonymous"></script>
这就是我为我的 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;
}
受到JD Smith奇妙的正则表达式解决方案的启发,我突然有了一个令人头晕目眩的想法:
var D = Date().toString().split(" ");
console.log(D[2] + "-" + D[1] + "-" + D[3]);
var today = new Date();
var formattedToday = today.toLocaleDateString() + ' ' + today.toLocaleTimeString();
截至 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
对于任何正在寻找一个非常简单的 ES6 解决方案来复制、粘贴和采用的人:
const dateToString = d => `${d.getFullYear()}-${('00' + (d.getMonth() + 1)).slice(-2)}-${('00' + d.getDate()).slice(-2)}`
// how to use:
const myDate = new Date(Date.parse('04 Dec 1995 00:12:00 GMT'))
console.log(dateToString(myDate)) // 1995-12-04
为了将日期格式化为 eg ,10-Aug-2010
您可能需要使用ES6数组解构。.toDateString()
const formattedDate = new Date().toDateString()
// The above yields e.g. 'Mon Jan 06 2020'
const [, month, day, year] = formattedDate.split(' ')
const ddMmmYyyy = `${day}-${month}-${year}`
// or
const ddMmmYyyy = [day, month, year].join('-')
Sugar.js 对 Date 对象有很好的扩展,包括Date.format方法。
文档中的示例:
Date.create().format('{Weekday} {Month} {dd}, {yyyy}');
Date.create().format('{12hr}:{mm}{tt}')
它在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',
hour: '2-digit',minute: '2-digit', second: '2-digit' }); //
const dtfUS = new Intl.DateTimeFormat('en', { year: 'numeric', month: '2-digit', day: '2-digit',
hour: '2-digit',minute: '2-digit', second: '2-digit' }); //
console.log(dtfUS.format(d)); // 08/05/2010 11:45:00 PM
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() + // Tue Aug 10 2010
' ' + d.toTimeString().split(' ')[0] + // 12:34:56, GMT+0x00 (GMT+0x:00)
' ' + (d.getMonth() + 101) + // 108
' ' + d.getMilliseconds(); // 789
console.log(str); // Tue Aug 10 2010 12:34:56 108 789
console.log(// $1 Tue $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)')
); // 10-Aug-2010 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 Month
$9: 789 Milliseconds
*/
或者例如 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)', new Date())
);
如果您不需要它们,您可以删除无用的部分和/或更改索引。
两个纯 JavaScript 单行代码
在这个答案中,我发展了JD Smith 的想法。我能够缩短 JD Smith 正则表达式。
let format= d=> d.toString().replace(/\w+ (\w+) (\d+) (\d+).*/,'$2-$1-$3');
console.log( format(Date()) );
Dave 的也是基于 JD Smith 的想法,但他避免使用正则表达式并给出了一个非常好的解决方案——我稍微缩短了他的解决方案(通过更改split参数)并在包装器中使其不透明。
let format= (d,a=d.toString().split` `)=> a[2]+"-"+a[1]+"-"+a[3];
console.log( format(Date()) );
要获得“2010 年 8 月 10 日”,请尝试:
var date = new Date('2010-08-10 00:00:00');
date = date.toLocaleDateString(undefined, {day:'2-digit'}) + '-' + date.toLocaleDateString(undefined, {month:'short'}) + '-' + date.toLocaleDateString(undefined, {year:'numeric'})
有关浏览器支持,请参阅toLocaleDateString。
尝试这个:
function init(){
var d = new Date();
var day = d.getDate();
var x = d.toDateString().substr(4, 3);
var year = d.getFullYear();
document.querySelector("#mydate").innerHTML = day + '-' + x + '-' + year;
}
window.onload = init;
<div id="mydate"></div>
DateFormatter.formatDate(new Date(2010,7,10), 'DD-MMM-YYYY')
=>10-Aug-2010
DateFormatter.formatDate(new Date(), 'YYYY-MM-DD HH:mm:ss')
=>2017-11-22 19:52:37
DateFormatter.formatDate(new Date(2005, 1, 2, 3, 4, 5), 'D DD DDD DDDD, M MM MMM MMMM, YY YYYY, h hh H HH, m mm, s ss, a A')
=>2 02 Wed Wednesday, 2 02 Feb February, 05 2005, 3 03 3 03, 4 04, 5 05, am AM
var DateFormatter = {
monthNames: [
"January", "February", "March", "April", "May", "June",
"July", "August", "September", "October", "November", "December"
],
dayNames: ["Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday"],
formatDate: function (date, format) {
var self = this;
format = self.getProperDigits(format, /d+/gi, date.getDate());
format = self.getProperDigits(format, /M+/g, date.getMonth() + 1);
format = format.replace(/y+/gi, function (y) {
var len = y.length;
var year = date.getFullYear();
if (len == 2)
return (year + "").slice(-2);
else if (len == 4)
return year;
return y;
})
format = self.getProperDigits(format, /H+/g, date.getHours());
format = self.getProperDigits(format, /h+/g, self.getHours12(date.getHours()));
format = self.getProperDigits(format, /m+/g, date.getMinutes());
format = self.getProperDigits(format, /s+/gi, date.getSeconds());
format = format.replace(/a/ig, function (a) {
var amPm = self.getAmPm(date.getHours())
if (a === 'A')
return amPm.toUpperCase();
return amPm;
})
format = self.getFullOr3Letters(format, /d+/gi, self.dayNames, date.getDay())
format = self.getFullOr3Letters(format, /M+/g, self.monthNames, date.getMonth())
return format;
},
getProperDigits: function (format, regex, value) {
return format.replace(regex, function (m) {
var length = m.length;
if (length == 1)
return value;
else if (length == 2)
return ('0' + value).slice(-2);
return m;
})
},
getHours12: function (hours) {
// https://stackoverflow.com/questions/10556879/changing-the-1-24-hour-to-1-12-hour-for-the-gethours-method
return (hours + 24) % 12 || 12;
},
getAmPm: function (hours) {
// https://stackoverflow.com/questions/8888491/how-do-you-display-javascript-datetime-in-12-hour-am-pm-format
return hours >= 12 ? 'pm' : 'am';
},
getFullOr3Letters: function (format, regex, nameArray, value) {
return format.replace(regex, function (s) {
var len = s.length;
if (len == 3)
return nameArray[value].substr(0, 3);
else if (len == 4)
return nameArray[value];
return s;
})
}
}
console.log(DateFormatter.formatDate(new Date(), 'YYYY-MM-DD HH:mm:ss'));
console.log(DateFormatter.formatDate(new Date(), 'D DD DDD DDDD, M MM MMM MMMM, YY YYYY, h hh H HH, m mm, s ss, a A'));
console.log(DateFormatter.formatDate(new Date(2005, 1, 2, 3, 4, 5), 'D DD DDD DDDD, M MM MMM MMMM, YY YYYY, h hh H HH, m mm, s ss, a A'));
格式描述取自Ionic Framework(它不支持Z
, UTC Timezone Offset)
未经过彻底测试
如果您喜欢一个简短的、人类可读的功能 - 这很容易调整以适合您。
timeStamp参数是从 1970 年开始的毫秒数 - 它由new Date().getTime()
许多其他设备返回......
好吧,我改变主意了。我包括一个额外的零填充功能。诅咒!
function zeroPad(aNumber) {
return ("0"+aNumber).slice(-2);
}
function humanTime(timeStamp) {
var M = ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec'];
var D = new Date(timeStamp); // 23 Aug 2016 16:45:59 <-- Desired format.
return D.getDate() + " " + M[D.getMonth()] + " " + D.getFullYear() + " " + D.getHours() + ":" + zeroPad(d.getMinutes()) + ":" + zeroPad(D.getSeconds());
}
我使用以下。它很简单并且工作正常。
var dtFormat = require('dtformat');
var today = new Date();
dtFormat(today, "dddd, mmmm dS, yyyy, h:MM:ss TT");
或这个:
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)
简短、广泛兼容的方法:
function formatDate(date) {
date.toISOString()
.replace(/^(\d+)-(\d+)-(\d+).*$/, // Only extract Y-M-D
function (a,y,m,d) {
return [
d, // Day
['Jan','Feb','Mar','Apr','May','Jun', // Month Names
'Jul','Ago','Sep','Oct','Nov','Dec']
[m-1], // Month
y // Year
].join('-') // Stitch together
})
}
或者,作为单行:
date.toISOString().replace(/^(\d+)-(\d+)-(\d+)T(\d+):(\d+):(\d+).(\d+)Z$/, function (a,y,m,d) {return [d,['Jan','Feb','Mar','Apr','May','Jun','Jul','Ago','Sep','Oct','Nov','Dic'][m-1],y].join('-')})
将jQuery UI插件添加到您的页面:
function DateFormate(dateFormate, datetime) {
return $.datepicker.formatDate(dateFormate, datetime);
};
有一个新库smarti.to.js用于 JavaScript 数字、日期和 JSON 日期(Microsoft 或 ISO8601)的本地化格式。
例子:
new Date('2015-1-1').to('dd.MM.yy') // Outputs 01.01.2015
"2015-01-01T10:11:12.123Z".to('dd.MM.yy') // Outputs 01.01.2015
本地化文件 (smarti.to.{culture}.js) 中还定义了自定义短模式。示例(smarti.to.et-EE.js):
new Date('2015-1-1').to('d') // Outputs 1.01.2015
和多格式能力:
smarti.format('{0:n2} + {1:n2} = {2:n2}', 1, 2, 3) // Output: 1,00 + 2,00 = 3,00
This function was inspired by Java's SimpleDateFormat provides various formats such as:
dd-MMM-yyyy → 17-Jul-2018
yyyyMMdd'T'HHmmssXX → 20180717T120856+0900
yyyy-MM-dd'T'HH:mm:ssXXX → 2018-07-17T12:08:56+09:00
E, dd MMM yyyy HH:mm:ss Z → Tue, 17 Jul 2018 12:08:56 +0900
yyyy.MM.dd 'at' hh:mm:ss Z → 2018.07.17 at 12:08:56 +0900
EEE, MMM d, ''yy → Tue, Jul 17, '18
h:mm a → 12:08 PM
hh 'o''''clock' a, X → 12 o'clock PM, +09
Code example:
function formatWith(formatStr, date, opts) {
if (!date) {
date = new Date();
}
opts = opts || {};
let _days = opts.days;
if (!_days) {
_days = ['Sun', 'Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat'];
}
let _months = opts.months;
if (!_months) {
_months = ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec'];
}
const pad = (number, strDigits, isUnpad) => {
const strNum = number.toString();
if (!isUnpad && strNum.length > strDigits.length) {
return strNum;
} else {
return ('0000' + strNum).slice(-strDigits.length);
}
};
const timezone = (date, letter) => {
const chunk = [];
const offset = -date.getTimezoneOffset();
chunk.push(offset === 0 ? 'Z' : offset > 0 ? '+' : '-');//add Z or +,-
if (offset === 0) return chunk;
chunk.push(pad(Math.floor(offset / 60), '00'));//hour
if (letter === 'X') return chunk.join('');
if (letter === 'XXX') chunk.push(':');
chunk.push(pad((offset % 60), '00'));//min
return chunk.join('');
};
const ESCAPE_DELIM = '\0';
const escapeStack = [];
const escapedFmtStr = formatStr.replace(/'.*?'/g, m => {
escapeStack.push(m.replace(/'/g, ''));
return ESCAPE_DELIM + (escapeStack.length - 1) + ESCAPE_DELIM;
});
const formattedStr = escapedFmtStr
.replace(/y{4}|y{2}/g, m => pad(date.getFullYear(), m, true))
.replace(/M{3}/g, m => _months[date.getMonth()])
.replace(/M{1,2}/g, m => pad(date.getMonth() + 1, m))
.replace(/M{1,2}/g, m => pad(date.getMonth() + 1, m))
.replace(/d{1,2}/g, m => pad(date.getDate(), m))
.replace(/H{1,2}/g, m => pad(date.getHours(), m))
.replace(/h{1,2}/g, m => {
const hours = date.getHours();
return pad(hours === 0 ? 12 : hours > 12 ? hours - 12 : hours, m);
})
.replace(/a{1,2}/g, m => date.getHours() >= 12 ? 'PM' : 'AM')
.replace(/m{1,2}/g, m => pad(date.getMinutes(), m))
.replace(/s{1,2}/g, m => pad(date.getSeconds(), m))
.replace(/S{3}/g, m => pad(date.getMilliseconds(), m))
.replace(/[E]+/g, m => _days[date.getDay()])
.replace(/[Z]+/g, m => timezone(date, m))
.replace(/X{1,3}/g, m => timezone(date, m))
;
const unescapedStr = formattedStr.replace(/\0\d+\0/g, m => {
const unescaped = escapeStack.shift();
return unescaped.length > 0 ? unescaped : '\'';
});
return unescapedStr;
}
// Let's format with above function
const dateStr = '2018/07/17 12:08:56';
const date = new Date(dateStr);
const patterns = [
"dd-MMM-yyyy",
"yyyyMMdd'T'HHmmssXX",//ISO8601
"yyyy-MM-dd'T'HH:mm:ssXXX",//ISO8601EX
"E, dd MMM yyyy HH:mm:ss Z",//RFC1123(RFC822) like email
"yyyy.MM.dd 'at' hh:mm:ss Z",//hh shows 1-12
"EEE, MMM d, ''yy",
"h:mm a",
"hh 'o''''clock' a, X",
];
for (let pattern of patterns) {
console.log(`${pattern} → ${formatWith(pattern, date)}`);
}
And you can use this as a library
It is also released as an NPM module. You can use this on Node.js or use this from a CDN for a browser.
Node.js
const {SimpleDateFormat} = require('@riversun/simple-date-format');
In the browser
<script src="https://cdn.jsdelivr.net/npm/@riversun/simple-date-format@1.0.2/dist/simple-date-format.js"></script>
Write the code as follows.
const date = new Date('2018/07/17 12:08:56');
const sdf = new SimpleDateFormat();
console.log(sdf.formatWith("yyyy-MM-dd'T'HH:mm:ssXXX", date));//to be "2018-07-17T12:08:56+09:00"
Source code here on GitHub:
yy
= 2 位数年份;
yyyy
= 全年
M
= 数字月份;
MM
= 2 位数的月份;
MMM
= 短月份名称;
MMMM
= 完整的月份名称
EEEE
= 完整的工作日名称;
EEE
= 简短的工作日名称
d
= 数字日;
dd
= 2 位数的日期
h
=小时;
hh
= 2 位数的小时数
m
=分钟;
mm
= 2 位数分钟
s
=秒;
ss
= 2 位数秒
S
= 毫秒
使用与类 SimpleDateFormat (Java)类似的格式
var monthNames = [
"January", "February", "March", "April", "May", "June", "July",
"August", "September", "October", "November", "December"
];
var dayOfWeekNames = [
"Sunday", "Monday", "Tuesday",
"Wednesday", "Thursday", "Friday", "Saturday"
];
function formatDate(date, formatStr){
if (!formatStr) {
formatStr = 'dd/mm/yyyy';
}
var day = date.getDate(),
month = date.getMonth(),
year = date.getFullYear(),
hour = date.getHours(),
minute = date.getMinutes(),
second = date.getSeconds(),
miliseconds = date.getMilliseconds(),
hh = twoDigitPad(hour),
mm = twoDigitPad(minute),
ss = twoDigitPad(second),
EEEE = dayOfWeekNames[date.getDay()],
EEE = EEEE.substr(0, 3),
dd = twoDigitPad(day),
M = month + 1,
MM = twoDigitPad(M),
MMMM = monthNames[month],
MMM = MMMM.substr(0, 3),
yyyy = year + "",
yy = yyyy.substr(2, 2)
;
return formatStr
.replace('hh', hh).replace('h', hour)
.replace('mm', mm).replace('m', minute)
.replace('ss', ss).replace('s', second)
.replace('S', miliseconds)
.replace('dd', dd).replace('d', day)
.replace('MMMM', MMMM).replace('MMM', MMM).replace('MM', MM).replace('M', M)
.replace('EEEE', EEEE).replace('EEE', EEE)
.replace('yyyy', yyyy)
.replace('yy', yy)
;
}
function twoDigitPad(num) {
return num < 10 ? "0" + num : num;
}
console.log(formatDate(new Date()));
console.log(formatDate(new Date(), 'EEEE, MMMM d, yyyy hh:mm:ss:S'));
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(), 'yy-MM-dd hh:mm'));
您可以格式化日期的其他方式:
function formatDate(dDate,sMode){
var today = dDate;
var dd = today.getDate();
var mm = today.getMonth()+1; //January is 0!
var yyyy = today.getFullYear();
if(dd<10) {
dd = '0'+dd
}
if(mm<10) {
mm = '0'+mm
}
if (sMode+""==""){
sMode = "dd/mm/yyyy";
}
if (sMode == "yyyy-mm-dd"){
return yyyy + "-" + mm + "-" + dd + "";
}
if (sMode == "dd/mm/yyyy"){
return dd + "/" + mm + "/" + yyyy;
}
}
这是修改为具有 3 个字符的月份和 2 个数字的年份的主要答案:
function formatDate(date) {
var monthNames = ["Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"];
var day = date.getDate(), monthIndex = date.getMonth(), year = date.getFullYear().toString().substr(-2);
return day + ' ' + monthNames[monthIndex] + ' ' + year;
}
document.write(formatDate(new Date()));
使用此程序
const MONTHS = ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sept', 'Oct', 'Nov', 'Dec']
const date = new Date()
const dateString = `${date.getDate()}-${MONTHS[date.getMonth()]}-${date.getFullYear()}`
console.log(dateString)
如果您已经在项目中使用 ExtJS ,则可以使用Ext.Date:
var date = new Date();
Ext.Date.format(date, "d-M-Y");
返回:
"11-Nov-2015"
我知道有人可能会说这是一个愚蠢的解决方案,但它确实通过从日期字符串中删除不必要的信息来解决问题。
yourDateObject
产生:
2017 年 12 月 13 日星期三 20:40:40 GMT+0200 (EET)
yourDateObject.toString().slice(0, 15);
产生:
2017 年 12 月 13 日,星期三
一个可以返回日期、日期+时间或仅返回时间的简单函数:
var myDate = dateFormatter("2019-01-24 11:33:24", "date-time");
// >> RETURNS "January 24, 2019 11:33:24"
var myDate2 = dateFormatter("2019-01-24 11:33:24", "date");
// >> RETURNS "January 24, 2019"
var myDate3 = dateFormatter("2019-01-24 11:33:24", "time");
// >> RETURNS "11:33:24"
function dateFormatter(strDate, format){
var theDate = new Date(strDate);
if (format=="time")
return getTimeFromDate(theDate);
else{
var dateOptions = {year:'numeric', month:'long', day:'numeric'};
var formattedDate = theDate.toLocaleDateString("en-US", + dateOptions);
if (format=="date")
return formattedDate;
return formattedDate + " " + getTimeFromDate(theDate);
}
}
function getTimeFromDate(theDate){
var sec = theDate.getSeconds();
if (sec<10)
sec = "0" + sec;
var min = theDate.getMinutes();
if (min<10)
min = "0" + min;
return theDate.getHours() + ':'+ min + ':' + sec;
}
您不需要任何库。只需提取日期组件并构造字符串。这是获取YYYY-MM-DD
格式的方法。另请注意月份索引“一月为 0,二月为 1,依此类推”。
// @flow
type Components = {
day: number,
month: number,
year: number
}
export default class DateFormatter {
// YYYY-MM-DD
static YYYY_MM_DD = (date: Date): string => {
const components = DateFormatter.format(DateFormatter.components(date))
return `${components.year}-${components.month}-${components.day}`
}
static format = (components: Components) => {
return {
day: `${components.day}`.padStart(2, '0'),
month: `${components.month}`.padStart(2, '0'),
year: components.year
}
}
static components = (date: Date) => {
return {
day: date.getDate(),
month: date.getMonth() + 1,
year: date.getFullYear()
}
}
}
function convert_month(i = 0, option = "num") { // i = index
var object_months = [
{ num: 01, short: "Jan", long: "January" },
{ num: 02, short: "Feb", long: "Februari" },
{ num: 03, short: "Mar", long: "March" },
{ num: 04, short: "Apr", long: "April" },
{ num: 05, short: "May", long: "May" },
{ num: 06, short: "Jun", long: "Juni" },
{ num: 07, short: "Jul", long: "July" },
{ num: 08, short: "Aug", long: "August" },
{ num: 09, short: "Sep", long: "September" },
{ num: 10, short: "Oct", long: "October" },
{ num: 11, short: "Nov", long: "November" },
{ num: 12, short: "Dec", long: "December" }
];
return object_months[i][option];
}
var d = new Date();
// https://stackoverflow.com/questions/1408289/how-can-i-do-string-interpolation-in-javascript
var num = `${d.getDate()}-${convert_month(d.getMonth())}-${d.getFullYear()}`;
var short = `${d.getDate()}-${convert_month(d.getMonth(), "short")}-${d.getFullYear()}`;
var long = `${d.getDate()}-${convert_month(d.getMonth(), "long")}-${d.getFullYear()}`;
document.querySelector("#num").innerHTML = num;
document.querySelector("#short").innerHTML = short;
document.querySelector("#long").innerHTML = long;
<p>Numeric : <span id="num"></span> (default)</p>
<p>Short : <span id="short"></span></p>
<p>Long : <span id="long"></span></p>
以下代码将允许您将日期格式化为DD-MM-YYYY
(27-12-2017) 或DD MMM YYYY
(27 Dec 2017) :
/** Pad number to fit into nearest power of 10 */
function padNumber(number, prependChar, count) {
var out = '' + number; var i;
if (number < Math.pow(10, count))
while (out.length < ('' + Math.pow(10, count)).length) out = prependChar + out;
return out;
}
/* Format the date to 'DD-MM-YYYY' or 'DD MMM YYYY' */
function dateToDMY(date, useNumbersOnly) {
var months = [
'Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct',
'Nov', 'Dec'
];
return '' + padNumber(date.getDate(), '0', 1) +
(useNumbersOnly? '-' + padNumber(date.getMonth() + 1, '0', 1) + '-' : ' ' + months[date.getMonth()] + ' ')
+ date.getFullYear();
}
date.getFullYear()
更改和的顺序padNumber(date.getDate(), '0', 1)
以生成dateToYMD()
函数。
有关详细信息,请参阅repl.it 示例。
该模块可以轻松处理几乎所有的情况。它是一个更大的 npm 包的一部分,由 Locutus 提供,其中包括各种功能,但它可以完全独立于包本身使用,如果不使用 npm,只需复制粘贴/适应一点(从模块更改为一个函数)。
作为第二个参数,它接受一个时间戳,它可以来自任何地方,例如 Date.getTime()。
此外,Locutus 维护了一个更大的 datetime 模块,也在locutus包中,这将提供一种更加面向对象的方式来使用它。
在这里,您可以看到其他日期时间函数(作为模块),它们也被证明非常有用。
您可以在此处找到有关参数和格式字符串的文档(请注意,文档站点是一个 PHP 站点,但 locutus 实现遵循完全相同的规范)。
日期模块示例
date('H:m:s \\m \\i\\s \\m\\o\\n\\t\\h', 1062402400)//'07:09:40 m is month'
date('F j, Y, g:i a', 1062462400)//'September 2, 2003, 12:26 am'
date('Y W o', 1062462400)//'2003 36 2003'
var $x = date('Y m d', (new Date()).getTime() / 1000) $x = $x + '' var $result = $x.length // 2009 01 09 10
date('W', 1104534000) //'52'
date('B t', 1104534000) //'999 31'
date('W U', 1293750000.82); // 2010-12-31 '52 1293750000'
date('W', 1293836400); // 2011-01-01 '52'
date('W Y-m-d', 1293974054); // 2011-01-02 '52 2011-01-02'
也许这有助于一些人愿意或意外地一个接一个地寻找多种日期格式。请找到代码:我在当前日期使用 Moment.js 格式函数(今天是 29-06-2020):var startDate = moment(new Date()).format('MM/DD/YY');
结果:06/28/20
它只保留年份部分:20 作为“06/28/20”,如果我运行该语句new Date(startDate)
,结果是“Mon Jun 28 1920 00:00:00 GMT+0530(印度标准时间)”。
然后,当我在“06/28/20”上使用另一种格式时: startDate = moment(startDate ).format('MM-DD-YYYY'); 结果:06-28-1920,在 Google Chrome 和 Firefox 浏览器中,第二次尝试的正确日期为:06-28-2020。
但在 Internet Explorer 中,它有问题。据我了解,我们可以在给定日期应用一种日期格式。如果我们想要第二种日期格式,它应该应用于新日期,而不是第一个日期格式结果。并且还观察到第一次应用 'MM-DD-YYYY' 和下一个 'MM-DD-YY' 在 Internet Explorer 中工作。为了清楚地理解,请在链接中找到我的问题:Date go wrong when using Moment.js date format in Internet Explorer 11。
这是一个完全符合您要求的脚本
https://github.com/UziTech/js-date-format
var d = new Date("2010-8-10");
document.write(d.format("DD-MMM-YYYY"));
利用:
thisDate = new Date(parseInt(jsonDateString.replace('/Date(', '')));
formattedDate = (thisDate.getMonth() + 1) + "/" + (thisDate.getDate()+1) + "/" + thisDate.getFullYear();
这需要一个JSON日期“/Date(1429573751663)/”,并生成格式化字符串:
“2015 年 4 月 21 日”
这是一些准备粘贴的时间/日期格式代码,不依赖任何外部模块/库或使用 jQuery 或 ES7 或任何东西。与其他一些答案中的代码不同,此代码提供了以下功能组合:
- 它需要一个 JavaScript Date 对象作为输入
- 它可以将日期显示为本地时区或 UTC
- 它使用简单的格式化系统“{year4} {month02} {second}”,即使在您编写代码之后也易于阅读和理解,不像典型的“%D %m %-”,它总是迫使您返回文档
- 格式化系统没有像一些特别的“DD MM YYYY”系统那样奇怪的自碰撞
- 你可以在这里运行测试并尝试一下
// format_date(date, pattern, utc)
// - date
// - a JavaScript Date object
// - use "new Date()" for current time
// - pattern
// - a string with embedded {codes} like
// "{year4}-{month02}-{day02}: {dayname3}"
// see format_date_funcs below for complete list
// - any other letters go through unchanged
// - utc
// - if true, shows date in UTC time "zone"
// - if false/omitted, shows date in local time zone
//
var month_names =
[
"January", "February", "March", "April", "May", "June", "July",
"August", "September", "October", "November", "December"
];
var day_of_week_names =
[
"Sunday", "Monday", "Tuesday",
"Wednesday", "Thursday", "Friday", "Saturday"
];
function space_pad2(num)
{
return num < 10 ? " " + num : num;
}
function zero_pad2(num)
{
return num < 10 ? "0" + num : num;
}
function space_pad3(num)
{
if (num < 10)
return " " + num;
else if (num < 100)
return " " + num;
else
return num;
}
function zero_pad3(num)
{
if (num < 10)
return "00" + num;
else if (num < 100)
return "0" + num;
else
return num;
}
var format_date_funcs =
{
// {year4} = '1902'
// {year02} = '02'
//
'year4': function(date, utc)
{
var year = utc ? date.getUTCFullYear() : date.getFullYear();
return year;
},
'year02': function(date, utc)
{
var year = utc ? date.getUTCFullYear() : date.getFullYear();
return year.toString().substr(2,2);
},
// {month} = '1' - '12'
// {month2} = ' 1' - '12' (space padded)
// {month02} = '01' - '12'
//
'month': function(date, utc)
{
var month = utc ? date.getUTCMonth() : date.getMonth(); // [0,11]
return month + 1;
},
'month2': function(date, utc)
{
var month = utc ? date.getUTCMonth() : date.getMonth(); // [0,11]
return space_pad2(month + 1);
},
'month02': function(date, utc)
{
var month = utc ? date.getUTCMonth() : date.getMonth(); // [0,11]
return zero_pad2(month + 1);
},
// {monthname} = 'January'
// {monthname3} = 'Jan'
//
'monthname': function(date, utc)
{
var month = utc ? date.getUTCMonth() : date.getMonth(); // [0,11]
return month_names[month];
},
'monthname3': function(date, utc)
{
var month = utc ? date.getUTCMonth() : date.getMonth(); // [0,11]
return month_names[month].substr(0, 3);
},
// {day} = '1' - '31'
// {day2} = ' 1' - '31' (space padded)
// {day02} = '01' - '31'
//
'day': function(date, utc)
{
var date = utc ? date.getUTCDate() : date.getDate(); // [1,31]
return date;
},
'day2': function(date, utc)
{
var date = utc ? date.getUTCDate() : date.getDate(); // [1,31]
return space_pad2(date);
},
'day02': function(date, utc)
{
var date = utc ? date.getUTCDate() : date.getDate(); // [1,31]
return zero_pad2(date);
},
// {dayname} = 'Tuesday'
// {dayname3} = 'Tue'
//
'dayname': function(date, utc)
{
var day = utc ? date.getUTCDay() : date.getDay(); // [0,6]
return day_of_week_names[day];
},
'dayname3': function(date, utc)
{
var day = utc ? date.getUTCDay() : date.getDay(); // [0,6]
return day_of_week_names[day].substr(0,3);
},
// {24hour} = '0' - '23'
// {24hour2} = ' 0' - '23' (space padded)
// {24hour02} = '00' - '23'
//
'24hour': function(date, utc)
{
var hour = utc ? date.getUTCHours() : date.getHours(); // [0,23]
return hour;
},
'24hour2': function(date, utc)
{
var hour = utc ? date.getUTCHours() : date.getHours(); // [0,23]
return space_pad2(hour);
},
'24hour02': function(date, utc)
{
var hour = utc ? date.getUTCHours() : date.getHours(); // [0,23]
return zero_pad2(hour);
},
// {12hour} = '1' - '12'
// {12hour2} = ' 1' - '12' (space padded)
// {12hour02} = '01' - '12'
// {ampm} = 'am' or 'pm'
// {AMPM} = 'AM' or 'PM'
//
'12hour': function(date, utc)
{
var hour = utc ? date.getUTCHours() : date.getHours(); // [0,23]
hour = hour % 12; // [0,11]
if (0 === hour) hour = 12;
return hour;
},
'12hour2': function(date, utc)
{
var hour = utc ? date.getUTCHours() : date.getHours(); // [0,23]
hour = hour % 12; // [0,11]
if (0 === hour) hour = 12;
return space_pad2(hour);
},
'12hour02': function(date, utc)
{
var hour = utc ? date.getUTCHours() : date.getHours(); // [0,23]
hour = hour % 12; // [0,11]
if (0 === hour) hour = 12;
return zero_pad2(hour);
},
'ampm': function(date, utc)
{
var hour = utc ? date.getUTCHours() : date.getHours(); // [0,23]
return (hour < 12 ? 'am' : 'pm');
},
'AMPM': function(date, utc)
{
var hour = utc ? date.getUTCHours() : date.getHours(); // [0,23]
return (hour < 12 ? 'AM' : 'PM');
},
// {minute} = '0' - '59'
// {minute2} = ' 0' - '59' (space padded)
// {minute02} = '00' - '59'
//
'minute': function(date, utc)
{
var minute = utc ? date.getUTCMinutes() : date.getMinutes(); // [0,59]
return minute;
},
'minute2': function(date, utc)
{
var minute = utc ? date.getUTCMinutes() : date.getMinutes(); // [0,59]
return space_pad2(minute);
},
'minute02': function(date, utc)
{
var minute = utc ? date.getUTCMinutes() : date.getMinutes(); // [0,59]
return zero_pad2(minute);
},
// {second} = '0' - '59'
// {second2} = ' 0' - '59' (space padded)
// {second02} = '00' - '59'
//
'second': function(date, utc)
{
var second = utc ? date.getUTCSeconds() : date.getSeconds(); // [0,59]
return second;
},
'second2': function(date, utc)
{
var second = utc ? date.getUTCSeconds() : date.getSeconds(); // [0,59]
return space_pad2(second);
},
'second02': function(date, utc)
{
var second = utc ? date.getUTCSeconds() : date.getSeconds(); // [0,59]
return zero_pad2(second);
},
// {msec} = '0' - '999'
// {msec3} = ' 0' - '999' (space padded)
// {msec03} = '000' - '999'
//
'msec': function(date, utc)
{
var msec =
utc ? date.getUTCMilliseconds() : date.getMilliseconds(); // [0,999]
return msec;
},
'msec3': function(date, utc)
{
var msec =
utc ? date.getUTCMilliseconds() : date.getMilliseconds(); // [0,999]
return space_pad3(msec);
},
'msec03': function(date, utc)
{
var msec =
utc ? date.getUTCMilliseconds() : date.getMilliseconds(); // [0,999]
return zero_pad3(msec);
},
// {open} = '{' (in case you actually want '{' in the output)
//
'open': function(date, utc)
{
return '{';
},
// {close} = '}' (in case you actually want '}' in the output)
//
'close': function(date, utc)
{
return '}';
},
};
function format_date(date, pattern, utc)
{
if (!pattern)
{
pattern = '{month}/{day}/{year4}';
}
var ret = '';
while (pattern.length > 0)
{
var s = pattern.indexOf('{');
var e = pattern.indexOf('}');
//console.log('s ' + s + ' e ' + e);
if (-1 !== s && -1 !== e && s < e)
{
// - there is a well-formed {foo} in range [s,e]
// - first we emit range [0,s) as literal
}
else
{
// - rest of string has no {} or has malformed }{ or { or }
// - just emit the rest of the string as literal and be done
s = pattern.length;
}
// emit range [0,s) as literal
if (s > 0)
{
ret += pattern.substr(0, s);
pattern = pattern.substr(s);
e -= s;
s = 0;
}
if (0 === pattern.length) break;
// emit range [s=0,e] by evaluating code
console.assert(0 === s); // position of {
console.assert(e > 0); // position of }
console.assert('{' === pattern.substr(s, 1));
console.assert('}' === pattern.substr(e, 1));
var code = pattern.substr(1,e-1);
var func = format_date_funcs[code];
console.assert(func);
ret += func(date, utc);
pattern = pattern.substr(e+1);
}
return ret;
}
if (1) // test format_date
{
var fmt = '[';
for (var func in format_date_funcs)
{
if (!format_date_funcs.hasOwnProperty(func)) continue;
fmt += '{' + func + '}/';
}
fmt += ']';
var now = new Date();
console.log(fmt);
console.log(format_date(now, fmt, false /* utc */));
console.log(format_date(now, fmt, true /* utc */));
}
2.39KB minified. One file. https://github.com/rhroyston/clock-js
10-Aug-2010 would be:
var str = clock.month
str.charAt(0).toUpperCase() + str.slice(1,3); //gets you "Aug"
console.log(clock.day + '-' + str + '-' + clock.year); //gets you 10-Aug-2010
这可以帮助:
export const formatDateToString = date => {
if (!date) {
return date;
}
try {
return format(parse(date, 'yyyy-MM-dd', new Date()), 'dd/MM/yyyy');
} catch (error) {
return 'invalid date';
}
};