/**
* 获取时间戳
* @
param date 日期:2017/03/03 13:49:55
* @
param num 当前日期的前或后推几年 /月 /天 /小时 /分钟 /秒
* @
param type yy 年 /mm 月 /dd 天 /h 小时 /m 分钟 /s 秒
* @
time 2017/08/31
* @
returns {string}
*/
function timestamps (date = '', num = 0, type = 'dd') {
let today;
if (date == '' || date == 0) {
today = Date.parse(new Date()).toString();
} else {
today = Date.parse(new Date(date)).toString();
}
let result = 0;
if (num != 0 && num != '') {
num = parseInt(num);
if(type == 'yy' || type == 'mm') {
let now;
if (date == '' || date == 0) {
now = new Date();
} else {
now = new Date(date);
}
let year = now.getFullYear();
let month = parseInt(now.getMonth()) + 1;
let day = now.getDate();
let hours = now.getHours();
let minutes = now.getMinutes();
let seconds = now.getSeconds();
if (type == 'yy') {
year = parseInt(year) + num;
} else {
if (num > 0) {
let m = parseInt(month) + num;
if (m > 12) {
let rem = m % 12;
let remint = Math.floor(m / 12);
if (rem != 0) {
year = parseInt(year) + remint;
month = rem;
} else {
year = parseInt(year) + remint -1;
month = '12';
}
} else {
month = m;
}
} else {
let m = parseInt(month) + num;
if (m == 0) {
year = parseInt(year) - 1;
month = '12';
} else if (m > 0) {
month = m;
} else {
if (m > -12) {
month = parseInt(m) + 12;
year = parseInt(year) - 1;
} else {
let rem = m % 12;
let remint = parseInt(m / 12) - 1;
month = parseInt(rem) + 12;
year = parseInt(year) + remint;
}
}
}
}
let format = this.getFormatDate(year, month, day);
let res_date = format[0] + '/' + format[1] + '/' + format[2] + ' ' + hours + ':' + minutes + ':' + seconds;
result = Date.parse(new Date(res_date)).toString();
} else if (type == 'h') {
result = today / 1000 + 3600 * num;
return result.toString();
} else if (type == 'm') {
result = today / 1000 + 60 * num;
return result.toString();
} else if (type == 's') {
result = today / 1000 + num;
return result.toString();
} else {
result = today / 1000 + 3600 * 24 * num;
return result.toString();
}
} else {
result = today;
}
return Math.round(result / 1000);
}
V2EX 是创意工作者们的社区,是一个分享自己正在做的有趣事物、交流想法,可以遇见新朋友甚至新机会的地方。
V2EX is a community of developers, designers and creative people.