我试图使用JS将日期对象转换为YYYYMMDD格式的字符串。有没有比连接Date.getYear(), Date.getMonth()和Date.getDay()更简单的方法?
当前回答
根据@o-o的答案,这将根据格式字符串返回日期的字符串。如果你需要的话,你可以很容易地为年份和毫秒添加一个2位数的年份正则表达式。
Date.prototype.getFromFormat = function(format) {
var yyyy = this.getFullYear().toString();
format = format.replace(/yyyy/g, yyyy)
var mm = (this.getMonth()+1).toString();
format = format.replace(/mm/g, (mm[1]?mm:"0"+mm[0]));
var dd = this.getDate().toString();
format = format.replace(/dd/g, (dd[1]?dd:"0"+dd[0]));
var hh = this.getHours().toString();
format = format.replace(/hh/g, (hh[1]?hh:"0"+hh[0]));
var ii = this.getMinutes().toString();
format = format.replace(/ii/g, (ii[1]?ii:"0"+ii[0]));
var ss = this.getSeconds().toString();
format = format.replace(/ss/g, (ss[1]?ss:"0"+ss[0]));
return format;
};
d = new Date();
var date = d.getFromFormat('yyyy-mm-dd hh:ii:ss');
alert(date);
然而,我不知道这有多高效,特别是在性能方面,因为它使用了大量的正则表达式。它可能会使用一些我不掌握纯js的工作。
注意:我保留了预定义的类定义,但你可能想把它放在一个函数或自定义类根据最佳实践。
其他回答
如果你不介意包含一个额外的(但很小的)库,Sugar.js为在JavaScript中处理日期提供了很多不错的功能。 格式化日期,使用format函数:
new Date().format("{yyyy}{MM}{dd}")
纯JS (ES5)解决方案,没有任何可能的日期跳转问题,由date . toisostring()打印UTC:
var now = new Date();
var todayUTC = new Date(Date.UTC(now.getFullYear(), now.getMonth(), now.getDate()));
return todayUTC.toISOString().slice(0, 10).replace(/-/g, '');
这是为了回应@weberste对@Pierre Guilbert的回答的评论。
当我需要这样做时,我通常使用下面的代码。
var date = new Date($.now());
var dateString = (date.getFullYear() + '-'
+ ('0' + (date.getMonth() + 1)).slice(-2)
+ '-' + ('0' + (date.getDate())).slice(-2));
console.log(dateString); //Will print "2015-09-18" when this comment was written
为了解释,.slice(-2)给出了字符串的最后两个字符。
所以无论如何,我们都可以在日期或月份后加上“0”,只要求最后两个,因为这两个总是我们想要的。
所以如果MyDate.getMonth()返回9,它将是:
("0" + "9") // Giving us "09"
加上。slice(-2)就得到了最后两个字符:
("0" + "9").slice(-2)
"09"
但是如果date.getMonth()返回10,它将是:
("0" + "10") // Giving us "010"
所以加上.slice(-2)会得到最后两个字符,或者:
("0" + "10").slice(-2)
"10"
[day,,month,,year]= Intl.DateTimeFormat(undefined, { year: 'numeric', month: '2-digit', day: '2-digit' }).formatToParts(new Date()),year.value+month.value+day.value
or
new Date().toJSON().slice(0,10).replace(/\/|-/g,'')
这段代码修复了Pierre Guilbert的答案:
(10000年后依然有效)
YYYYMMDD=new Date().toISOString().slice(0,new Date().toISOString().indexOf("T")).replace(/-/g,"")
推荐文章
- 如何将两个字符串相加,就好像它们是数字一样?
- 绑定多个事件到一个监听器(没有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