JavaScript
var date = new Date()
function showTime(d){
console.log(d.getFullYear() + '-' + (d.getMonth() + 1) + '-' + d.getDate() + ' ' +
d.getHours() + ':' + d.getMinutes() + ':' + d.getSeconds());
}
showTime(date);
//两位对齐 不足两位补0
function formatTime(d){
function format(n){
let tmp = n.toString();
return tmp.length === 1 ? '0' + tmp : tmp;
}
return d.getFullYear() + '-' + format(d.getMonth() + 1) + '-' + format(d.getDate()) + ' ' +
format(d.getHours()) + ':' + format(d.getMinutes()) + ':' + format(d.getSeconds());
}
function addYear(n,_d) {
let d = _d?_d:new Date();
d.setFullYear(d.getFullYear()+ n);
return d;
}
function addMonth(n,_d) {
let d = _d?_d:new Date();
d.setMonth(d.getMonth()+ n);
return d;
}
function addDay(n,_d){
let d = _d?_d:new Date();
d.setDate(d.getDate()+ n);
return d;
}
function addSecond(n,_d) {
let d = _d?_d:new Date();
d.setSeconds(d.getSeconds() + n);
return d;
}
showTime(addYear(1));
时间分割函数设计:
export const splitTime = t => {
const f = s => {
return s.toString().padStart(2, '0')
}
let d = new Date(t * 1000)
let year = d.getFullYear().toString()
let month = f(d.getMonth()+1)
let date = f(d.getDate())
let hour = f(d.getHours())
let minute = f(d.getMinutes())
let second = f(d.getSeconds())
return {year, month, date, hour, minute, second}
}