如何将Date对象格式化为字符串?
当前回答
在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,'-'));
结果是:“2017年10月12日”
可以使用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".
选项
可选择的具有以下部分或全部财产的对象:
本地匹配器
要使用的区域设置匹配算法。可能的值是“查找”和“最佳匹配”;默认值为“最佳拟合”。有关此选项的信息,请参阅Intl页面。
时区
要使用的时区。实现必须识别的唯一值是“UTC”;默认值是运行时的默认时区。实施还可以识别IANA时区数据库的时区名称,例如“亚洲/上海”、“亚洲/加尔各答”、“美国/纽约”。
小时12
是否使用12小时(而不是24小时)。可能的值为true和false;默认值取决于区域设置。
格式匹配器
要使用的格式匹配算法。可能的值是“基本”和“最适合”;默认值为“最佳拟合”。有关使用此属性的信息,请参见以下段落。
以下财产描述了格式化输出中使用的日期时间组件及其所需的表示。需要实现至少支持以下子集:
weekday, year, month, day, hour, minute, second
weekday, year, month, day
year, month, day
year, month
month, day
hour, minute, second
hour, minute
实现可能支持其他子集,并且将针对所有可用的子集表示组合来协商请求,以找到最佳匹配。有两种算法可用于此协商,并由formatMatcher属性选择:完全指定的“基本”算法和依赖于实现的“最佳匹配”算法。
周工作日
工作日的表示。可能的值有“窄”、“短”、“长”。
era
时代的代表。可能的值有“窄”、“短”、“长”。
year
年度的表示。可能的值为“数字”、“2位数”。
月
月份的表示。可能的值有“数字”、“2位数”、“窄”、“短”、“长”。
day
当天的表示。可能的值为“数字”、“2位数”。
hour
小时的表示。可能的值为“数字”、“2位数”。
分钟
会议记录的表示。可能的值为“数字”、“2位数”。
第二
第二个的表示。可能的值为“数字”、“2位数”。
时区名称
时区名称的表示形式。可能的值为“短”、“长”。每个日期时间组件属性的默认值未定义,但如果所有组件财产均未定义,则假定年、月和日为“数字”。
联机检查
更多详细信息
其他回答
大家好,我有一个代码,用于为日期添加日期和格式。
const FechaMaxima = new Date();
FechaMaxima.setDate(FechaMaxima.getDate() + 6);
FechaMaxima.toISOString().substring(0, 10);
包装解决方案: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。
函数convert_month(i=0,option=“num”){//i=索引变量对象月=[{num:01,短:“Jan”,长:“Janer”},{num:02,短:“Feb”,长:“Februari”},{num:03,短:“Mar”,长:“March”},{num:04,短:“Apr”,长:“April”},{num:05,短:“May”,长:“May”},{num:06,短:“Jun”,长:“Juni”},{num:07,短:“Jul”,长:“July”},{num:08,短:“Aug”,长:“August”},{num:09,短:“Sep”,长:“Sept”},{num:10,短:“Oct”,长:“Octo”},{num:11,短:“Nov”,长:“十一月”},{num:12,短:“Dec”,长:“十二月”}];返回object_months[i][option];}var d=新日期();// https://stackoverflow.com/questions/1408289/how-can-i-do-string-interpolation-in-javascriptvar 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=短;document.querySelector(“#long”).innerHTML=long;<p>数字:<span id=“num”></span>(默认值)</p><p>短:<span id=“Short”></span></p><p>长:<span id=“Long”></span></p>
字体版本
可以轻松增强以支持所需的任何格式字符串。当这样的通用解决方案非常容易创建,并且应用程序中经常出现日期格式时,我不建议在应用程序中对日期格式代码进行硬编码。这很难读懂,也隐藏了你的意图。格式字符串清楚地显示您的意图。
原型函数
interface Date {
format(formatString: string): string;
}
Date.prototype.format = function (formatString: string): string {
return Object.entries({
YYYY: this.getFullYear(),
YY: this.getFullYear().toString().substring(2),
yyyy: this.getFullYear(),
yy: this.getFullYear().toString().substring(2),
MMMM: this.toLocaleString('default', { month: 'long' }),
MMM: this.toLocaleString('default', { month: 'short' }),
MM: (this.getMonth() + 1).toString().padStart(2, '0'),
M: this.getMonth() + 1,
DDDD: this.toLocaleDateString('default', { weekday: 'long' }),
DDD: this.toLocaleDateString('default', { weekday: 'short' }),
DD: this.getDate().toString().padStart(2, '0'),
D: this.getDate(),
dddd: this.toLocaleDateString('default', { weekday: 'long' }),
ddd: this.toLocaleDateString('default', { weekday: 'short' }),
dd: this.getDate().toString().padStart(2, '0'),
d: this.getDate(),
HH: this.getHours().toString().padStart(2, '0'), // military
H: this.getHours().toString(), // military
hh: (this.getHours() % 12).toString().padStart(2, '0'),
h: (this.getHours() % 12).toString(),
mm: this.getMinutes().toString().padStart(2, '0'),
m: this.getMinutes(),
SS: this.getSeconds().toString().padStart(2, '0'),
S: this.getSeconds(),
ss: this.getSeconds().toString().padStart(2, '0'),
s: this.getSeconds(),
TTT: this.getMilliseconds().toString().padStart(3, '0'),
ttt: this.getMilliseconds().toString().padStart(3, '0'),
AMPM: this.getHours() < 13 ? 'AM' : 'PM',
ampm: this.getHours() < 13 ? 'am' : 'pm',
}).reduce((acc, entry) => {
return acc.replace(entry[0], entry[1].toString())
}, formatString)
}
Javascript版本
同样,只需删除接口,以及冒号及其关联冒号之后的类型名称。
demo
function unitTest() {
var d: Date = new Date()
console.log(d.format('MM/dd/yyyy hh:mm:ss')) // 12/14/2022 03:38:31
console.log(d.format('yyyy-MM-dd HH:mm:ss')) // 2022-12-14 15:38:31
}
unitTest()
字符串转换
// date
const dateConvert = {
dasher: dt => {
let m = (dt.getMonth() + 1) === 13 ? 1 : (dt.getMonth() + 1);
m = m < 10 ? `0${m}` : m.toString();
let d = dt.getDate();
d = d < 10 ? `0${d}` : d.toString();
return `${dt.getFullYear()}-${m}-${d}`;
},
slasher: dt => {
return dateConvert.slash(dateConvert.dasher(dt));
},
dash: str => {
// 03/11/2022 -> 2022-03-11
let [d, m, y] = str.split('/');
return `${y}-${m}-${d}`;
},
slash: str => {
// 2022-03-11 -> 03/11/2022
let [y, m, d] = str.split('-');
return `${d}/${m}/${y}`
}
}
// console.log(dateConvert.dasher(new Date('01/31/2001')));