这篇博客主要为了总结平时常用的时间处理方法,方便以后使用
一、获取传入日期的时间戳
// 转时间戳方法
getTime(timeStr) {
return new Date(timeStr).getTime();
}
二、获取传入日期的年月日
// 获取年月日
getSpecificDate(timeStr) {
const date = new Date(timeStr);
const year = date.getFullYear();
const month = date.getMonth() + 1;
const day = date.getDate();
return year + '-' + (month < 10 ? '0' : "") + month + '-' + (day < 10 ? '0' : "") + day;
}
三、获取传入日期的时分秒
// 获取时分秒
getTimeDivision(timeStr) {
const date = new Date(timeStr);
const hours = date.getHours();
const minutes = date.getMinutes();
const seconds = date.getSeconds();
return (hours < 10 ? '0' : "") + hours + ':' + (minutes < 10 ? '0' : "") + minutes + ':' + (seconds < 10 ? '0' :
"") + seconds;
}
四、获取当前时间的年月日时分秒
getCurrentTime() {
let date = new Date();
let year = date.getFullYear(); // 年
let month = date.getMonth() + 1; // 月
let day = date.getDate(); // 日
let hour = date.getHours(); // 时
hour = hour < 10 ? "0" + hour : hour; // 如果只有一位,则前面补零
let minute = date.getMinutes(); // 分
minute = minute < 10 ? "0" + minute : minute; // 如果只有一位,则前面补零
let second = date.getSeconds(); // 秒
second = second < 10 ? "0" + second : second; // 如果只有一位,则前面补零
return year + "-" + month + "-" + day + " " + hour + ":" + minute + ":" + second;
}
五、获取当前日期的前后n天日期
getDay(day) {
var today = new Date();
var targetday_milliseconds = today.getTime() + 1000 * 60 * 60 * 24 * day;
today.setTime(targetday_milliseconds); //注意,这行是关键代码
var tYear = today.getFullYear();
var tMonth = today.getMonth();
var tDate = today.getDate();
tMonth = this.doHandleMonth(tMonth + 1);
tDate = this.doHandleMonth(tDate);
return tYear + "-" + tMonth + "-" + tDate;
}
doHandleMonth(month) {
var m = month;
if (month.toString().length == 1) {
m = "0" + month;
}
return m;
}
六、获取当前时间的前后n小时
// 加减几小时计算
getHoursCount(time, num) {
return this.getCurrentTime(new Date(time).getTime() + num * 60 * 60 * 1000);
}
这世界很喧嚣,做你自己就好