前端开发小技巧js-时间处理
-
获取当天0点0分0秒(date格式)
export function getTime1() {
var date = new Date();
date.setHours(0);
date.setMinutes(0);
date.setSeconds(0);
return date;
}
-
获取当天23点59分59秒(date格式)
export function getTime2() {
var date = new Date();
date.setHours(23);
date.setMinutes(59);
date.setSeconds(59);
return date;
}
-
获取上月这天(date格式,到秒)
export function getLastMonthTime() {
var date = new Date(new Date().getTime() - 30 * 24 * 3600 * 1000);
return date;
}
秒转为时分秒格式
export function formatSeconds(value) {
var theTime = parseInt(value); // 秒
if (theTime > 60) {
var h = Math.floor(theTime / 3600);
var m = Math.floor((theTime / 60 % 60)) < 10 ? '0' + Math.floor((theTime / 60 % 60)) : Math.floor((theTime / 60 % 60));
var s = Math.floor((theTime % 60)) < 10 ? '0' + Math.floor((theTime % 60)) : Math.floor((theTime % 60));
return value = h + "h" + m + "''" + s + "'";
} else {
var s = Math.floor((theTime % 60)) < 10 ? '0' + Math.floor((theTime % 60)) : Math.floor((theTime % 60));
return s + "'";
}
}
h和秒之间加个空格?(...要求)
export function forMateTime(obj) {
if (obj) {
if (obj.indexOf('h') > 0) {
return obj.split('h')[0] + 'h ' + obj.split('h')[1];
} else {
return obj
}
} else {
return '--';
}
}
date格式转为字符串格式
export function padLeftZero(str) {
return ("00" + str).substr(str.length);
}
export function formatDate(date, fmt) {
if (/(y+)/.test(fmt)) {
fmt = fmt.replace(
RegExp.$1,
(date.getFullYear() + "").substr(4 - RegExp.$1.length)
);
}
let o = {
"M+": date.getMonth() + 1,
"d+": date.getDate(),
"h+": date.getHours(),
"m+": date.getMinutes(),
"s+": date.getSeconds()
};
for (let k in o) {
if (new RegExp(`(${k})`).test(fmt)) {
let str = o[k] + "";
fmt = fmt.replace(
RegExp.$1,
RegExp.$1.length === 1 ? str : padLeftZero(str)
);
}
}
return fmt;
}
let date = new Date();
let time = formatDate(date, "yyyy-MM-dd hh:mm:ss");//yyyy-MM-dd hh:mm:ss hh:mm:ss