我试图使用JS将日期对象转换为YYYYMMDD格式的字符串。有没有比连接Date.getYear(), Date.getMonth()和Date.getDay()更简单的方法?
当前回答
[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,'')
其他回答
我经常使用的一段修改代码:
Date.prototype.yyyymmdd = function() {
var mm = this.getMonth() + 1; // getMonth() is zero-based
var dd = this.getDate();
return [this.getFullYear(),
(mm>9 ? '' : '0') + mm,
(dd>9 ? '' : '0') + dd
].join('');
};
var date = new Date();
date.yyyymmdd();
这个帖子中最受欢迎的答案的简化版本https://stackoverflow.com/a/3067896/5437379:
function toYYYYMMDD(d) {
var yyyy = d.getFullYear().toString();
var mm = (d.getMonth() + 101).toString().slice(-2);
var dd = (d.getDate() + 100).toString().slice(-2);
return yyyy + mm + dd;
}
我不喜欢修改本机对象,而且我认为乘法比填充接受的解决方案的字符串更清楚。
函数yyyymmdd(dateIn) { var yyyy = dateIn.getFullYear(); var mm = dateIn.getMonth() + 1;// getMonth()是从零开始的 var dd = dateIn.getDate(); 返回String(10000 * yyyy + 100 * mm + dd);// mm和dd的前导零 } var today = new Date(); console.log(名称(今天));
小提琴:http://jsfiddle.net/gbdarren/Ew7Y4/
似乎mootools提供了Date().format(): https://mootools.net/more/docs/1.6.0/Types/Date
但我不确定是否值得只针对这个特定的任务。
Day.js怎么样?
它只有2KB,你还可以使用dayjs().format('YYYY-MM-DD')。
https://github.com/iamkun/dayjs
推荐文章
- 如何将两个字符串相加,就好像它们是数字一样?
- 绑定多个事件到一个监听器(没有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