如何将Date对象格式化为字符串?
当前回答
自定义格式设置函数:
对于固定格式,一个简单的函数即可完成任务。以下示例生成国际格式YYYY-MM-DD:
函数dateToYMD(日期){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(新日期(2017,10,5));//11月5日
OP格式可以如下生成:
函数dateToYMD(日期){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();返回“”+(d<=9?“0”+d:d)+“-”+“+m+”-“+y;}console.log(dateToYMD(新日期(2017,10,5));//11月5日
注意:然而,扩展JavaScript标准库通常不是一个好主意(例如,通过将此函数添加到Date的原型中)。
更高级的功能可以基于格式参数生成可配置的输出。
如果编写一个格式化函数太长,那么周围有很多库可以执行它。其他一些答案已经列举了它们。但日益增加的依赖性也有反作用。
标准ECMAScript格式化函数:
自从ECMAScript的最新版本以来,Date类具有一些特定的格式化函数:
toDateString:依赖于实现,仅显示日期。https://262.ecma-international.org/#sec-日期.协议类型.日期new Date().toDateString();//例如“2016年11月11日星期五”
toISOString:显示ISO 8601日期和时间。https://262.ecma-international.org/#sec-日期.协议类型.toisostringnew Date().toISOString();//例如“2016-11-21T08:00:00.000Z”
toJSON:JSON的Stringer。https://262.ecma-international.org/#sec-日期.原型.项目new Date().toJSON();//例如“2016-11-21T08:00:00.000Z”
toLocaleDateString:依赖于实现,区域设置格式的日期。https://262.ecma-international.org/#sec-日期.协议类型.颜色日期字符串new Date().toLocaleDateString();//例如“2016年11月21日”
toLocaleString:依赖于实现,是区域设置格式的日期和时间。https://262.ecma-international.org/#sec-日期.协议类型.颜色字符串new Date().toLocaleString();//例如“2016年11月21日上午08:00:00”
toLocaleTimeString:依赖于实现,以区域设置格式表示时间。https://262.ecma-international.org/#sec-日期.协议类型.颜色时间字符串new Date().toLocaleTimeString();//例如“08:00:00 AM”
toString:日期的通用toString。https://262.ecma-international.org/#sec-日期.协议类型.测试new Date().toString();//例如“2016年11月21日星期五08:00:00 GMT+0100(西欧标准时间)”
注意:可以使用这些格式生成自定义输出>
new Date().toISOString().slice(0,10)//返回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));
指定标准函数的区域设置:
上面列出的一些标准函数取决于语言环境:
到LocaleDateString()到LocaleTimeString()到LocalString()
这是因为不同的文化使用不同的格式,并以不同的方式表达他们的日期或时间。默认情况下,该函数将返回在其运行的设备上配置的格式,但这可以通过设置参数(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' })
示例片段:console.log(“1)”+new Date().toLocaleString('en-US'));console.log(“2)”+new Date().toLocaleString('ko-KR'));console.log(“3)”+新日期().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到UTC的转换可能具有挑战性(考虑到DST、时区不是1小时的倍数等)。尽可能使用经过良好测试的库。不要假设语言环境与一个国家相关:几个国家都有很多语言环境(加拿大、印度等)避免通过非标准方式检测区域设置。在这里,您可以了解到多个陷阱:检测键盘布局、按地理位置检测区域设置等。。
其他回答
该函数的灵感来自Java的SimpleDateFormat。它提供各种格式,例如:
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
代码示例:
函数formatWith(formatStr,date,opts){if(!date){date=新日期();}opts=opts||{};let _days=opts.days;如果(!_days){_days=[星期日、星期一、星期二、星期三、星期四、星期五、星期六];}let _months=opts.months;如果(!_months){_months=['Jan','Feb','Mar','Apr','May','Jun','Jul','Aug','Sep','Oct','Nov','Dec'];}常量pad=(number,strDigits,isUnpad)=>{const strNum=number.toString();如果(!isUnpad&&strNum.length>strDigits.length){返回strNum;}其他{return('0000'+strNum).sslice(-strDigits.length);}};常量时区=(日期,字母)=>{常量块=[];const offset=-date.getTimezoneOffset();chunk.push(偏移量==0?“Z”:偏移量>0?“+”:“-”)//添加Z或+-如果(偏移量==0)返回块;chunk.push(pad(数学地板(偏移量/60),“00”))//小时if(letter==“X”)返回chunk.join(“”);if(letter=='XXX')chunk.push(':');chunk.push(pad((偏移量%60),'00'))//最小值return chunk.join(“”);};const ESCAPE_DELIM=“\0”;常量escapeStack=[];const escapedFmtStr=格式Str.替换(/'.*?'/g,m=>{escapeStack.push(m.replace(/'/g,''));return ESCAPE_DELIM+(escapeStack.length-1)+ESCAPE_DELIM;});常量格式化Str=转义FmtStr.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)).替换(/h{1,2}/g,m=>{const hours=date.getHours();返回垫(小时==0?12:小时>12?小时-12:小时,m);}).replace(/a{1,2}/g,m=>date.getHours()>=12?'下午:上午).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()]).替换(/[Z]+/g,m=>时区(日期,m)).替换(/X{1,3}/g,m=>时区(日期,m));const unescapedStr=格式化Str.替换(/\0\d+\0/g,m=>{const unescaped=escapeStack.shift();返回unscaped.length>0?未转义:“\”;});返回unscapedStr;}//让我们用上面的函数格式化const dateStr='2018/07/17 12:08:56';const date=新日期(dateStr);常量模式=[“年-月-日”,“yyyyMMdd''HHmmssXX”,//ISO8601“yyyy-MM-dd''HH:MM:ssXXX”,//ISO8601EX“E,dd MMM yyyy HH:mm:ss Z”,//RFC1123(RFC822)类似电子邮件“yyyy.MM.dd'at'hh:MM:ss Z”,//hh显示1-12“EEE,MMM d,'yy”,“h:mm a”,“hh'o'''时钟'a,X”,];for(let模式){console.log(`${pattern}→ ${formatWith(pattern,date)}`);}
你可以把它当作图书馆
它也作为NPM模块发布。您可以在Node.js上使用它,也可以在浏览器的CDN中使用它。
节点.js
const {SimpleDateFormat} = require('@riversun/simple-date-format');
在浏览器中
<script src="https://cdn.jsdelivr.net/npm/@riversun/simple-date-format@1.0.2/dist/simple-date-format.js"></script>
按照以下步骤编写代码。
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"
GitHub上的源代码:
https://github.com/riversun/simple-date-format
这是我实现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;
}
这是我刚刚编写的一些代码,用于处理我正在处理的项目的日期格式。它模仿了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
*
************************************/
受到JD Smith奇妙的正则表达式解决方案的启发,我突然有了一个令人震惊的想法:
var D=Date().toString().split(“”);console.log(D[2]+“-”+D[1]+“-“+D[3]);
对于自定义分隔日期格式,必须拉出日期(或时间)DateTimeFormat对象(它是ECMAScript国际化API),然后手动创建字符串使用所需的分隔符。
为此,可以使用DateTimeFormat#formatToParts。你可以销毁数组,但这并不理想,因为数组输出取决于区域设置:
{//示例1设f=新Intl.DateTimeFormat('en');让a=f.formatToParts();控制台日志(a);}{//示例2设f=新Intl.DateTimeFormat('hi');让a=f.formatToParts();控制台日志(a);}
最好将格式数组映射到结果字符串:
函数连接(t,a,s){函数格式(m){设f=新Intl.DateTimeFormat('en',m);返回f.format(t);}返回.map(格式).join(s);}让a=〔{日:‘数字’},{月:‘短’}、{年:‘数字”}〕;let s=join(新日期,a,'-');console.log;
还可以使用DateTimeFormat#格式,但请注意,使用此方法时,截至3月2020年,当涉及到分钟和秒的前导零(该方法避免了此错误以上)。
设d=新日期(2010,7,5);let ye=新Intl.DateTimeFormat('en',{year:'numeric'}).format(d);let mo=新Intl.DateTimeFormat('en',{month:'short'}).format(d);let da=新Intl.DateTimeFormat('en',{day:'2-位'}).format(d);console.log(`${da}--${mo}-${ye}');
在处理日期和时间时,通常值得使用库(例如,luxon、date fns、moment.js不建议用于新项目),因为该领域有许多隐藏的复杂性。
注意,上述解决方案中使用的ECMAScript国际化APIIE10不支持(2月全球浏览器市场份额为0.03%)2020).
推荐文章
- 一元加/数字(x)和parseFloat(x)之间的区别是什么?
- angularjs中的compile函数和link函数有什么区别
- 删除绑定中添加的事件监听器
- 很好的初学者教程socket.io?
- HtmlSpecialChars在JavaScript中等价于什么?
- React: 'Redirect'没有从' React -router-dom'中导出
- 如何在React中使用钩子强制组件重新渲染?
- 我如何使用Jest模拟JavaScript的“窗口”对象?
- 我如何等待一个承诺完成之前返回一个函数的变量?
- 在JavaScript中根据键值查找和删除数组中的对象
- 使嵌套JavaScript对象平放/不平放的最快方法
- 如何以及为什么'a'['toUpperCase']()在JavaScript工作?
- 有Grunt生成index.html不同的设置
- 文档之间的区别。addEventListener和window。addEventListener?
- 如何检查动态附加的事件监听器是否存在?