如何将Date对象格式化为字符串?
当前回答
@Sébastien——可选的所有浏览器支持
new Date(parseInt(496407600)*1000).toLocaleDateString('de-DE', {
year: 'numeric',
month: '2-digit',
day: '2-digit'
}).replace(/\./g, '/');
文档:https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date/toLocaleDateString
基于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"
其他回答
好的,我们有一个叫做Intl的东西,这对在JavaScript中格式化日期非常有用:
您的日期如下:
var date = '10/8/2010';
然后使用如下所示的新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文档。
简单格式化程序:
function fmt(date, format = 'YYYY-MM-DDThh:mm:ss') {
const pad2 = (n) => n.toString().padStart(2, '0');
const map = {
YYYY: date.getFullYear(),
MM: pad2(date.getMonth() + 1),
DD: pad2(date.getDate()),
hh: pad2(date.getHours()),
mm: pad2(date.getMinutes()),
ss: pad2(date.getSeconds()),
};
return Object.entries(map).reduce((prev, entry) => prev.replace(...entry), format);
}
用法:
fmt(new Date(), 'YYYY-MM-DDThh:mm:ss'); // '2022-11-07T12:47:59'
对于自定义分隔日期格式,必须拉出日期(或时间)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).
自定义格式设置函数:
对于固定格式,一个简单的函数即可完成任务。以下示例生成国际格式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小时的倍数等)。尽可能使用经过良好测试的库。不要假设语言环境与一个国家相关:几个国家都有很多语言环境(加拿大、印度等)避免通过非标准方式检测区域设置。在这里,您可以了解到多个陷阱:检测键盘布局、按地理位置检测区域设置等。。
@Sébastien——可选的所有浏览器支持
new Date(parseInt(496407600)*1000).toLocaleDateString('de-DE', {
year: 'numeric',
month: '2-digit',
day: '2-digit'
}).replace(/\./g, '/');
文档:https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date/toLocaleDateString
基于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"
推荐文章
- 在数组中获取所有选中的复选框
- 如何在java中格式化持续时间?(如格式H:MM:SS)
- 如何为Firebase构建云函数,以便从多个文件部署多个函数?
- 如何发送推送通知到web浏览器?
- AngularJS:工厂和服务?
- js:将一个组件包装成另一个组件
- 父ng-repeat从子ng-repeat的访问索引
- JSHint和jQuery: '$'没有定义
- 模仿JavaScript中的集合?
- 用JavaScript验证电话号码
- 如何在HTML5中改变视频的播放速度?
- 谷歌地图API v3:我可以setZoom后fitBounds?
- ES6/2015中的null安全属性访问(和条件赋值)
- 与push()相反;
- JS字符串“+”vs concat方法