如何将Date对象格式化为字符串?


当前回答

你应该看看DayJs。它是momentJs的翻版,但模块化架构更轻。

快速2kB替代Moment.js,具有相同的现代API

Day.js是一个极简的JavaScript库,它使用Moment.js兼容的API为现代浏览器解析、验证、操作和显示日期和时间。如果您使用Moment.js,您已经知道如何使用Day.js。

var date=date.now();const formatedDate=dayjs(日期).format(“YYYY-MM-DD”)console.log(formatedDate);<script src=“https://cdnjs.cloudflare.com/ajax/libs/dayjs/1.8.16/dayjs.min.js“crossoorigin=”匿名“></script>

其他回答

它在InternetExplorer11、Firefox和Chrome中的工作方式相同(当选择en-UK时,Chrome80.x显示12小时格式)。

const d=新日期('2010/08/05 23:45')//26.3.2020const dtfUK=新Intl.DateTimeFormat('UK',{年:'数字',月:'2位数',日:'2位',小时:'2-位数',分钟:'2-位',秒:'2-数位'})//const dtfUS=新Intl.DateTimeFormat('en',{年:'数字',月:'2位数',日:'2位',小时:'2-位数',分钟:'2-位',秒:'2-数位'})//console.log(dtfUS.format(d));//2010年5月8日下午11:45:00console.log(dtfUK.format(d));//05.08.2010 23:45:00/*node.js:2010年5月8日,晚上11:45:002010-08-05 23:45:00*/

有什么更一般的吗?

var d=新日期('2010-08-10T10:34:56.789Z');var str=d.toDateString()+/-2010年8月10日星期二“”+d.toTimeString().split(“”)[0]+/-12:34:56,GMT+0x0(GMT+00:00)“”+(d.getMonth()+101)+/-108“”+d.获取毫秒();//789console.log(str);//2010年8月10日星期二12:34:56 108 789console.log(//$1周二$2 8月$3 11$4 2020$5 12$6 34$7 56$8 108$9 789str.replace(/(\S{3})(\S}3)(\d{1,2})); // 2010年8月10日12:34.789(星期二)/*$1:星期二工作日字符串$2:8月短文本$3:11天$4:2010年$5:12小时$6:34分钟$7:56秒$8:08个月$9:789毫秒*/

或例如1行IIFE“库”;-)

控制台日志((函数(frm,d){return[d.toDateString(),d.toTimeString().split(“”)[0],(d.getMonth()+101),d.getMilliseconds()].jjoin(“).replace(/(\S{3})(\S})('$4/$8/$3$5:$6($1)',新日期()));

如果不需要,可以删除无用的部件和/或更改索引。

使用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);

这可能有助于解决问题:

var d=新日期();var选项={day:'数字',月份:'long',年份:'数字'};console.log(d.toLocaleDateString('en-ZA',选项));

Sugar.js对Date对象有很好的扩展,包括Date.format方法。

文档中的示例:

Date.create().format('{Weekday} {Month} {dd}, {yyyy}');

Date.create().format('{12hr}:{mm}{tt}')

你应该看看DayJs。它是momentJs的翻版,但模块化架构更轻。

快速2kB替代Moment.js,具有相同的现代API

Day.js是一个极简的JavaScript库,它使用Moment.js兼容的API为现代浏览器解析、验证、操作和显示日期和时间。如果您使用Moment.js,您已经知道如何使用Day.js。

var date=date.now();const formatedDate=dayjs(日期).format(“YYYY-MM-DD”)console.log(formatedDate);<script src=“https://cdnjs.cloudflare.com/ajax/libs/dayjs/1.8.16/dayjs.min.js“crossoorigin=”匿名“></script>