如何将Date对象格式化为字符串?
当前回答
对于自定义分隔日期格式,必须拉出日期(或时间)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).
其他回答
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时区偏移)
未彻底测试
在现代浏览器(*)中,您可以这样做:
var today = new Date().toLocaleDateString('en-GB', {
day : 'numeric',
month : 'short',
year : 'numeric'
}).split(' ').join('-');
如果今天(1月24日)执行输出ᵗʰ, 2016):
'24-Jan-2016'
(*)根据MDN,“现代浏览器”是指Chrome 24+、Firefox 29+、Internet Explorer 11、Edge 12+、Opera 15+和Safari夜间版本。
对于任何想要复制、粘贴和采用真正简单的ES6解决方案的人来说:
const dateToString=d=>`${d.getFullYear()}-${('00'+(d.getMonth()+1)).slice(-2)}-${('0'+d.getDate()).spice(-2)}`//如何使用:const myDate=新日期(Date.parse('04 Dec 1995 00:12:00 GMT'))console.log(dateToString(myDate))//1995-12-04
截至2019年,您似乎可以使用LocaleDateString仅返回某些部分,然后您可以根据需要加入它们:
var date = new Date();
console.log(date.toLocaleDateString("en-US", { day: 'numeric' })
+ "-"+ date.toLocaleDateString("en-US", { month: 'short' })
+ "-" + date.toLocaleDateString("en-US", { year: 'numeric' }) );
> 16-Nov-2019
console.log(date.toLocaleDateString("en-US", { month: 'long' })
+ " " + date.toLocaleDateString("en-US", { day: 'numeric' })
+ ", " + date.toLocaleDateString("en-US", { year: 'numeric' }) );
> November 16, 2019
大家好,我有一个代码,用于为日期添加日期和格式。
const FechaMaxima = new Date();
FechaMaxima.setDate(FechaMaxima.getDate() + 6);
FechaMaxima.toISOString().substring(0, 10);
推荐文章
- 如何将两个字符串相加,就好像它们是数字一样?
- 绑定多个事件到一个监听器(没有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