我试图使用JS将日期对象转换为YYYYMMDD格式的字符串。有没有比连接Date.getYear(), Date.getMonth()和Date.getDay()更简单的方法?
当前回答
回答另一个简单性和可读性的问题。 此外,不鼓励使用新方法编辑现有的预定义类成员:
function getDateInYYYYMMDD() {
let currentDate = new Date();
// year
let yyyy = '' + currentDate.getFullYear();
// month
let mm = ('0' + (currentDate.getMonth() + 1)); // prepend 0 // +1 is because Jan is 0
mm = mm.substr(mm.length - 2); // take last 2 chars
// day
let dd = ('0' + currentDate.getDate()); // prepend 0
dd = dd.substr(dd.length - 2); // take last 2 chars
return yyyy + "" + mm + "" + dd;
}
var currentDateYYYYMMDD = getDateInYYYYMMDD();
console.log('currentDateYYYYMMDD: ' + currentDateYYYYMMDD);
其他回答
我经常使用的一段修改代码:
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();
下面是一种更通用的方法,它允许日期和时间组件,并且可以作为数字或字符串进行相同的排序。
根据“Date ISO format”中的数字顺序,转换为本地时区,去掉非数字。例如:
// monkey patch version
Date.prototype.IsoNum = function (n) {
var tzoffset = this.getTimezoneOffset() * 60000; //offset in milliseconds
var localISOTime = (new Date(this - tzoffset)).toISOString().slice(0,-1);
return localISOTime.replace(/[-T:\.Z]/g, '').substring(0,n || 20); // YYYYMMDD
}
使用
var d = new Date();
// Tue Jul 28 2015 15:02:53 GMT+0200 (W. Europe Daylight Time)
console.log(d.IsoNum(8)); // "20150728"
console.log(d.IsoNum(12)); // "201507281502"
console.log(d.IsoNum()); // "20150728150253272"
const date = new Date()
console.log(date.toISOString().split('T')[0]) // 2022-12-27
似乎mootools提供了Date().format(): https://mootools.net/more/docs/1.6.0/Types/Date
但我不确定是否值得只针对这个特定的任务。
我不喜欢修改本机对象,而且我认为乘法比填充接受的解决方案的字符串更清楚。
函数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/
推荐文章
- 如何为Firebase构建云函数,以便从多个文件部署多个函数?
- 如何发送推送通知到web浏览器?
- AngularJS:工厂和服务?
- js:将一个组件包装成另一个组件
- 父ng-repeat从子ng-repeat的访问索引
- JSHint和jQuery: '$'没有定义
- 模仿JavaScript中的集合?
- 用JavaScript验证电话号码
- 如何在HTML5中改变视频的播放速度?
- 谷歌地图API v3:我可以setZoom后fitBounds?
- ES6/2015中的null安全属性访问(和条件赋值)
- 与push()相反;
- JS字符串“+”vs concat方法
- AngularJS使用ng-class切换类
- 访问Handlebars.js每次循环范围之外的变量