如何将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>
其他回答
注意(2022-10):toLocaleFormat已被弃用一段时间,并从Firefox版本58中删除。请参见LocaleFormat
我想你可以使用非标准的Date方法来LocaleFormat(formatString)
formatString:与C中strftime()函数期望的格式相同的格式字符串。
var today = new Date();
today.toLocaleFormat('%d-%b-%Y'); // 30-Dec-2011
参考文献:
到区域设置格式斯特夫蒂姆
两个纯JavaScript单行程序
在这个答案中,我发展了JD Smith的想法。我能够缩短JD-Smith正则表达式。
let format=d=>d.toString().replace(/\w+(\w+)(\d+)(\d+).*/,'$2-$1-$3');console.log(格式(Date()));
Dave的也是基于JD Smith的想法,但他避免了正则表达式,并给出了一个非常好的解决方案——我稍微缩短了他的解决方案(通过更改拆分参数),并在包装器中使其不透明。
let format=(d,a=d.toString().split``)=>a[2]+“-”+a[1]+“-“+a[3];console.log(格式(Date()));
DateFormatter.formatDate(新日期(2010,7,10),'DD-MMM-YYYY')
=>2010年8月10日
DateFormatter.formatDate(new Date(),'YYYY-MM-DD HH:MM:ss')
=>2017-11-22 19:52:37
DateFormatter.formatDate(新日期(2005,1,2,3,4,5),'D DD DDD DDD,M MM MMM MMMM,YY YYYY,h hh h hh,M MM,s ss,a a')
=>2002年2月2日星期三2005年2月5日,2003年3月3日,4月4日,5月5日上午
var日期格式设置工具={月份名称:[“一月”,“二月”,“三月”,“四月”,“五月”,“六月”,“七月”、“八月”、“九月”、“十月”、“十一月”、“十二月”],dayName:[“星期日”、“星期一”、“周二”、“周三”、“周四”、“周五”、“周六”],formatDate:函数(日期,格式){var self=this;format=self.getProperDigits(format,/d+/gi,date.getDate());format=self.getProperDigits(格式,/M+/g,date.getMonth()+1);format=format.replace(/y+/gi,函数(y){var len=y.length;var year=date.getFullYear();如果(长度==2)return(年份+“”).sslice(-2);否则如果(len==4)回归年;返回y;})format=self.getProperDigits(格式,/H+/g,date.getHours());format=self.getProperDigits(格式,/h+/g,self.getHours12(date.getHours()));format=self.getProperDigits(format,/m+/g,date.getMinutes());format=self.getProperDigits(format,/s+/gi,date.getSeconds());format=format.replace(/a/ig,函数(a){var amPm=self.getAmPm(date.getHours())如果(a==“a”)返回amPm.toUpperCase();返回amPm;})format=self.getFullOr3Letters(format,/d+/gi,self.dayNames,date.getDay())format=self.getFullOr3Letters(format,/M+/g,self.monthNames,date.getMonth())返回格式;},getProperDigits:函数(格式、正则表达式、值){return format.replace(正则表达式,函数(m){var长度=m.length;如果(长度==1)返回值;否则如果(长度==2)return(“0”+值).sslice(-2);返回m;})},getHours12:函数(小时){// https://stackoverflow.com/questions/10556879/changing-the-1-24-hour-to-1-12-hour-for-the-gethours-method返回(小时+24)%12||12;},getAmPm:函数(小时){// https://stackoverflow.com/questions/8888491/how-do-you-display-javascript-datetime-in-12-hour-am-pm-format回程时间>=12?'下午':'上午';},getFullOr3Letters:函数(格式,正则表达式,名称数组,值){return format.replace(正则表达式,函数){var len=s.length;如果(长度==3)return nameArray[value].substr(0,3);否则如果(len==4)return nameArray[value];返回s;})}}console.log(DateFormatter.formatDate(new Date(),'YYYY-MM-DD HH:MM:ss'));console.log(DateFormatter.formatDate(new Date(),'D DD DDD DDDD,M MM MMM MMMM,YY YYYY,h hh h hh,M MM,s ss,a a'));console.log(DateFormatter.formatDate(新日期(2005,1,2,3,4,5),'D DD DDD DDDD,M MM MMM MMMM,YY YYYY,h hh h hh,M MM,s ss,a a'));
格式描述取自Ionic Framework(它不支持Z、UTC时区偏移)
未彻底测试
自定义格式设置函数:
对于固定格式,一个简单的函数即可完成任务。以下示例生成国际格式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小时的倍数等)。尽可能使用经过良好测试的库。不要假设语言环境与一个国家相关:几个国家都有很多语言环境(加拿大、印度等)避免通过非标准方式检测区域设置。在这里,您可以了解到多个陷阱:检测键盘布局、按地理位置检测区域设置等。。
函数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>
推荐文章
- 如何将两个字符串相加,就好像它们是数字一样?
- 绑定多个事件到一个监听器(没有JQuery)?
- 在JavaScript中将JSON字符串解析为特定对象原型
- 将字符串“true”/“false”转换为布尔值
- 如何使用JavaScript代码获得浏览器宽度?
- event.preventDefault()函数在IE中无法工作
- indexOf()和search()的区别是什么?
- 错误:'types'只能在.ts文件中使用- Visual Studio Code使用@ts-check
- React-Native:应用程序未注册错误
- LoDash:从对象属性数组中获取值数组
- src和dist文件夹的作用是什么?
- jQuery UI对话框-缺少关闭图标
- SQL Developer只返回日期,而不是时间。我怎么解决这个问题?
- 如何使用AngularJS获取url参数
- 将RGB转换为白色的RGBA