如何利用js获取时间数据,以下有一些常用方法:
方法 | 描述 |
---|---|
getDate() | 返回Number,1-31 |
getDay() | 返回Number,0-6 |
getYear() | 返回当前年份,2位 |
getFullYear() | 返回年份yyyy |
getHours() | 返回小时(24小时制,即0-23) |
getMilliseconds() | 返回毫秒,0-999 |
getMinutes() | 返回分,0-59 |
getMonth() | 返回月份,0-11 |
getSeconds() | 返回秒,0-59 |
getTime() | 返回当前时间,1970.1.1至今的毫秒数 |
toLocaleDateString() | 返回当前日期 |
toLocaleTimeString() | 返回当前时间 |
toLocaleString() | 返回日期与时间 |
若想要实现获取时间,且格式为:‘yyyy-MM-dd’,函数实现如下:
//判断时分秒是否小于10秒,是则在前面添加0,保持两位数
changeFormat(n) { return n < 10 ? '0' + n : n },
getNowTime: function () {
let date = new Date();
let month = date.getMonth() + 1;
let strDate = date.getDate();
if (month >= 1 && month <= 9) {
month = "0" + month;
}
if (strDate >= 0 && strDate <= 9) {
strDate = "0" + strDate;
}
let currentdate = date.getFullYear() + "-" + month + "-" + strDate
+ " " + this.changeFormat(date.getHours()) + ":" + this.changeFormat(date.getMinutes())
+ ":" + this.changeFormat(date.getSeconds());
return currentdate;
},