1 前言
1.1 业务场景
JavaScript计算两个时间相隔了 多少年多少月多少日。时分秒这里不作考虑。
2 实现原理
2.1 获取当前时间
若需要和当前时间比较,这里提供当前时间的获取格式化方法。我这里是根据传入类型输出日期或者日期+时间,可以明显看出type为day时,输出日期。
getNowDate(type){
let now = new Date()
let year = now.getFullYear()
let month = now.getMonth() + 1
let day = now.getDate()
let hh = now.getHours()
let mm = now.getMinutes()
let ss = now.getSeconds()
month = month < 10 ? '0'+ month : month
day = day < 10 ? '0'+ day : day
if(type == 'day'){
return year +'-'+ month +'-'+ day
} else {
return year +'-'+ month +'-'+ day + ' '+ hh + ':' + mm + ':' + ss