把以下文件复制到一个文件内,命名为 timeObj.js
然后直接引用即可。
let timeObj = {};
/**
* 生成当前日期时间
* @returns {string}
*/
timeObj.createDateTime = function(){
let date = new Date();
return date.getFullYear() + '-' + (date.getMonth() + 1) + '-' + date.getDate() + ' ' + date.getHours() + ':' + date.getMinutes() + ':' + date.getSeconds();
};
/**
* 生成前天日期
* @returns {string}
*/
timeObj.createBeforeYesterday = function(){
let today_date = new Date();
let hour = today_date.getHours();
if(hour >= 0 && hour <= 5 ){
today_date.setTime(today_date.getTime() - 24 * (2+1) * 60 * 60 * 1000);
}else{
today_date.setTime(today_date.getTime() - 24 * 2 * 60 * 60 * 1000);
}
let month = today_date.getMonth() + 1;
if(month < 10){
month = '0' + month;
}
let date = today_date.getDate();
if(date < 10){
date = '0' + date;
}
return today_date.getFullYear() + '-' + month + '-' + date;
};
/**
* 生成昨天日期
* @returns {string}
*/
timeObj.createYesterday = function(){
let today_date = new Date();
let hour = today_date.getHours();
if(hour >= 0 && hour <= 5 ){
today_date.setTime(today_date.getTime() - 24 * (1 + 1) * 60 * 60 * 1000);
}else{
today_date.setTime(today_date.getTime() - 24 * 1 * 60 * 60 * 1000);
}
let month = today_date.getMonth() + 1;
if(month < 10){
month = '0' + month;
}
let date = today_date.getDate();
if(date < 10){
date = '0' + date;
}
return today_date.getFullYear() + '-' + month + '-' + date;
};
/**
* 生成七天前日期
* @returns {string}
*/
timeObj.createSevendaysago = function(){
let today_date = new Date();
let hour = today_date.getHours();
if(hour >= 0 && hour <= 5 ){
today_date.setTime(today_date.getTime() - 24 * (7 + 1) * 60 * 60 * 1000);
}else{
today_date.setTime(today_date.getTime() - 24 * 7 * 60 * 60 * 1000);
}
let month = today_date.getMonth() + 1;
if(month < 10){
month = '0' + month;
}
let date = today_date.getDate();
if(date < 10){
date = '0' + date;
}
return today_date.getFullYear() + '-' + month + '-' + date;
};
/**
* 生成三十天前日期
* @returns {string}
*/
timeObj.createThirtydaysago = function(){
let today_date = new Date();
let hour = today_date.getHours();
if(hour >= 0 && hour <= 5 ){
today_date.setTime(today_date.getTime() - 24 * (30 + 1) * 60 * 60 * 1000);
}else{
today_date.setTime(today_date.getTime() - 24 * 30 * 60 * 60 * 1000);
}
let month = today_date.getMonth() + 1;
if(month < 10){
month = '0' + month;
}
let date = today_date.getDate();
if(date < 10){
date = '0' + date;
}
return today_date.getFullYear() + '-' + month + '-' + date;
};
/**
* 生成时间戳
*/
timeObj.getTime = function (){
return new Date().getTime();
};