我试图使用JS将日期对象转换为YYYYMMDD格式的字符串。有没有比连接Date.getYear(), Date.getMonth()和Date.getDay()更简单的方法?
当前回答
当我需要这样做时,我通常使用下面的代码。
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"
其他回答
这篇文章帮助我写了这个助手,所以我分享它以防有人 正在寻找这个解决方案,它支持yyyy, mm, dd的所有变化
Date.prototype.formattedDate = function (pattern) {
formattedDate = pattern.replace('yyyy', this.getFullYear().toString());
var mm = (this.getMonth() + 1).toString(); // getMonth() is zero-based
mm = mm.length > 1 ? mm : '0' + mm;
formattedDate = formattedDate.replace('mm', mm);
var dd = this.getDate().toString();
dd = dd.length > 1 ? dd : '0' + dd;
formattedDate = formattedDate.replace('dd', dd);
return formattedDate;
};
d = new Date();
pattern = 'yyyymmdd'; // 20150813
d.formattedDate(pattern);
pattern = 'yyyy-mm-dd';
d.formattedDate(pattern); // 2015-08-13
这里有一个简洁的小函数,易于阅读,并避免了局部变量,这在JavaScript中可能是时间消耗。我不使用原型来修改标准模块,因为它会污染名称空间,并可能导致代码不能执行您认为应该执行的操作。
main函数有一个愚蠢的名字,但它传达了思想。
function dateToYYYYMMDDhhmmss(date) {
function pad(num) {
num = num + '';
return num.length < 2 ? '0' + num : num;
}
return date.getFullYear() + '/' +
pad(date.getMonth() + 1) + '/' +
pad(date.getDate()) + ' ' +
pad(date.getHours()) + ':' +
pad(date.getMinutes()) + ':' +
pad(date.getSeconds());
}
Dateformat是一个非常常用的包。
使用方法:
从NPM下载并安装dateformat。在你的模块中需要它:
以格式
然后格式化你的东西:
const myYYYYmmddDate = dateformat(new Date(), 'yyyy-mm-dd');
这是一行代码,您可以使用它来创建今天日期的YYYY-MM-DD字符串。
var d = new Date().toISOString().slice(0,10);
@o-o解对我没用。 我的解决方案如下:
Date.prototype.yyyymmdd = function() {
var mm = this.getMonth() + 1; // getMonth() is zero-based
var dd = this.getDate();
var ret = [this.getFullYear(), (mm<10)?'0':'', mm, (dd<10)?'0':'', dd].join('');
return ret; // padding
};
推荐文章
- 如何为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每次循环范围之外的变量