如何将Date对象格式化为字符串?
当前回答
以下代码将允许您将日期格式设置为DD-MM-YYYY(2017年12月27日)或DD-MM-YYYY(2017年10月26日):
/** 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示例。
其他回答
包装解决方案:Luxon或date fns
如果你想使用一个解决方案来适应所有人,我建议使用date fns或Luxon。
Luxon托管在Moment.js网站上,由Moment.jss开发人员开发,因为Momentjs具有开发人员想解决但无法解决的局限性。
要安装:
npm安装luxon或纱线添加luxon(其他安装方法请访问链接)
例子:
luxon.DateTime.fromISO('2010-08-10').toFormat('yyyy-LL-dd');
产量:
2010年8月10日
手动解决方案
使用与Moment.js、ClassDateTimeFormatter(Java)和ClassSimpleDateFormat(Java)类似的格式,我实现了一个全面的解决方案formatDate(date,patternStr),代码易于阅读和修改。您可以显示日期、时间、AM/PM等。有关更多示例,请参阅代码。
例子:
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=上午/下午两位数小时;H=小时;HH=2位数小时
m=分钟;mm=2位数分钟;aaa=上午/下午
s=秒;ss=2位数秒
S=毫秒
var month名称=[“一月”,“二月”,“三月”,“四月”,“五月”,“六月”,“七月”,“八月”、“九月”、“十月”、“十一月”、“十二月”];var dayOfWeekNames=[“星期日”、“星期一”、“周二”,“周三”、“周四”、“周五”、“周六”];函数formatDate(日期,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=两位数广告(h),HH=两位数(小时),mm=两个DigitPad(分钟),ss=twoDigitPad(秒),aaa=小时<12?'上午:下午,EEEE=dayOfWeekNames[date.getDay()],EEE=EEEE.substr(0,3),dd=twoDigitPad(天),M=月+1,MM=两个DigitPad(M),MMMM=monthNames[月],MMM=MMMM.substr(0,3),yyyy=年+“”,yy=yyyy.substr(2,2);//检查是否将使用月份名称patternStr=patternStr.替换('h',hh).替换('h',h)替换('HH',HH)替换('H',小时).替换('m',mm).替换(m',分钟).替换('s',ss).替换(s'',second).replace('S',毫秒)替换('dd',dd)替换('d',day)替换('EEE',EEEE)替换('EE',EEE)替换('yyyy',yyyy).替换('yy',yy).替换('aaa',aaa);如果(patternStr.indexOf('MMM')>-1){patternStr=patternStr.替换('MMMM',MMMM).替换('MMM',MMM);}其他{patternStr=patternStr.替换('MM',MM).替换(M’,M);}返回模式Str;}函数twoDigitPad(num){返回num<10?“0”+num:num;}console.log(formatDate(newDate()));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:mmaa'));
谢谢你@Gerry提起Luxon。
使用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);
以下代码将允许您将日期格式设置为DD-MM-YYYY(2017年12月27日)或DD-MM-YYYY(2017年10月26日):
/** 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示例。
这是我刚刚编写的一些代码,用于处理我正在处理的项目的日期格式。它模仿了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
*
************************************/
截至2019年,您似乎可以使用LocaleDateString仅返回某些部分,然后您可以根据需要加入它们:
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
推荐文章
- 为什么我的球(物体)没有缩小/消失?
- 如何使用jQuery检测页面的滚动位置
- if(key in object)或者if(object. hasownproperty (key)
- 一元加/数字(x)和parseFloat(x)之间的区别是什么?
- angularjs中的compile函数和link函数有什么区别
- 删除绑定中添加的事件监听器
- 很好的初学者教程socket.io?
- HtmlSpecialChars在JavaScript中等价于什么?
- React: 'Redirect'没有从' React -router-dom'中导出
- 如何在React中使用钩子强制组件重新渲染?
- 我如何使用Jest模拟JavaScript的“窗口”对象?
- 我如何等待一个承诺完成之前返回一个函数的变量?
- 在JavaScript中根据键值查找和删除数组中的对象
- 使嵌套JavaScript对象平放/不平放的最快方法
- 如何以及为什么'a'['toUpperCase']()在JavaScript工作?