整理一些比较常用的日期格式转换function
1.日期格式化(转年月日时分秒)
//日期格式化(转年月日时分秒)
dateFormat:function(datetime){
let date = new Date(datetime);
let year = date.getFullYear();
let month = date.getMonth() + 1;
let day = date.getDate();
let hour = date.getHours();
let minute = date.getMinutes();
let second = date.getSeconds();
return year + "-" + this.formatTen(month) + "-" + this.formatTen(day)+ " " +this.formatTen(hour)+ ":" +this.formatTen(minute)+ ":" +this.formatTen(second);
},
formatTen:function (num) {
return num > 9 ? (num + "") : ("0" + num);
}
2.获取n个月前的第一天
//n个月前的第一天
monthStartDay:function (n) {
let today = new Date();
today.setMonth(today.getMonth()-n);
let y = today.getFullYear();
let m = today.getMonth()+1;
return y+'-'+this.formatTen(m)+'-01';
},
formatTen:function (num) {
return num > 9 ? (num + "") : ("0" + num);
},
3.获取近n个月的开始时间(n=6 近六个月)
//获取近n个月的开始时间
getMonthDay:function(n){
let today = new Date();
today.setMonth(today.getMonth()-n);
let y = today.getFullYear();
let m = today.getMonth()+1;
let d = today.getDate();
return y+'-'+this.formatTen(m)+'-'+this.formatTen(d);
},
formatTen:function (num) {
return num > 9 ? (num + "") : ("0" + num);
},
4.获取近n天的日期(day= -7 近七天;day=0 当天)
//获取近n天的日期(day=-7 近七天;day=0 当天)
getDay:function (day) {
let today = new Date();
let targetDayStamp=today.getTime() + 1000*60*60*24*day;
today.setTime(targetDayStamp); //注意,这行是关键代码
let year = today.getFullYear();
let month = today.getMonth();
let date = today.getDate();
return year+"-"+this.formatTen(month + 1)+"-"+this.formatTen(date);
},
formatTen:function (num) {
return num > 9 ? (num + "") : ("0" + num);
},
常见的日期格式
- 中国标准时间(newDate() 直接输出的就是这种格式):
Sat May 23 2020 22:35:47 GMT+0800 (中国标准时间) - UTC 协调世界时(后台偶尔会返回这类格式的数据接口)
2020-02-22T09:12:43.083Z - GMT-格林尼治标准时(new Date().toGMTString())
Sat, 23 May 2020 14:41:34 GMT - 时间戳(new Date().getTime())
1590244981126