nodejs时间函数

nodejs基础总结

    • moment时间函数应用
    • dayjs时间函数应用
      • 当前时间
      • format()根据传入的占位符返回格式化后的日期。
      • startOf()设置一个时间的开始
      • Add()增加时间
      • subtract()减少时间
      • toDate()返回原生的时间对象

moment时间函数应用

// 格式化时间	
moment('2017-09-01').format('YYYYMMDD')
// 当前时间 
moment().format('YYYY-MM-DD HH:mm:ss');
// 当前时间
now = moment();
// 格式化结束时间
endMoment = moment(endDate, 'YYYYMM');
// 结束时间距离当前时间的间隔
now.diff(endMoment, 'months')

// 前1周
startDate = moment(now.join(''), 'YYYYw').startOf('week').add(1, 'day').format('YYYY-MM-DD 00:00:00');
endDate = moment(now.join(''), 'YYYYw').endOf('week').add(1, 'day').format('YYYY-MM-DD 23:59:59');
// 前2周
lastStartDate = moment(now.join(''), 'YYYYw').subtract(1, 'week').startOf('week').add(1, 'day').format('YYYY-MM-DD 00:00:00');
lastEndDate = moment(now.join(''), 'YYYYw').subtract(1, 'week').endOf('week').add(1, 'day').format('YYYY-MM-DD 23:59:59');
// 前1月
startDate = moment(now.join(''), 'YYYYMM').startOf('month').format('YYYY-MM-DD 00:00:00');
endDate = moment(now.join(''), 'YYYYMM').endOf('month').format('YYYY-MM-DD 23:59:59');
// 前2月
lastStartDate = moment(now.join(''), 'YYYYMM').subtract(1, 'month').startOf('month').format('YYYY-MM-DD 00:00:00');
lastEndDate = moment(now.join(''), 'YYYYMM').subtract(1, 'month').endOf('month').format('YYYY-MM-DD 23:59:59');


// 一年的开始日期
const startYear = dayjs().startOf('year');
// 一年的结束日期
const endYear = dayjs().endOf('year');

// 当前时间
const current = dayjs().startOf('day');
// 一年已经过去了多少天 不连今天
const yearStartDay = current.diff(dayjs().startOf('year'), "day");
// 一年还剩余多少天
const yearEndDay = dayjs().endOf('year').diff(current, "day");

dayjs时间函数应用

当前时间

const current = dayjs();
// 当前年
return dayjs().year();

format()根据传入的占位符返回格式化后的日期。

dayjs('2019-01-25').format('DD/MM/YYYY') // '25/01/2019'
dayjs('2019-01-25').format('YYYY-MM-DD HH:mm:ss') // '2019-01-25 00:00:00'

标识 示例 描述
YY 18 年,两位数
YYYY 2018 年,四位数
M 1-12 月,从1开始
MM 01-12 月,两位数字
MMM Jan-Dec 月,英文缩写
D 1-31
DD 01-31 日,两位数
H 0-23 24小时
HH 00-23 24小时,两位数
h 1-12 12小时
hh 01-12 12小时,两位数
m 0-59 分钟
mm 00-59 分钟,两位数
s 0-59
ss 00-59 秒,两位数
S 0-9 毫秒 (百),一位数
SS 00-99 毫秒(十),两位数
SSS 000-999 毫秒,三位数
Z -05:00 UTC偏移
ZZ -0500 UTC偏移,两位数
A AM / PM 上/下午,大写
a am / pm 上/下午,小写
Do 1st… 31st 月份的日期与序号

startOf()设置一个时间的开始

// 设置一个时间的开始
dayjs().startOf('year');
// 设置一个时间的末尾
dayjs().endOf('month')
单位 缩写 详情
year y 今年一月1日上午 00:00
quarter Q 本季度第一个月1日上午 00:00 ( 依赖 QuarterOfYear 插件 )
month M 本月1日上午 00:00
week w 本周的第一天上午 00:00
isoWeek 本周的第一天上午 00:00 (根据 ISO 8601) ( 依赖 IsoWeek 插件 )
date D 当天 00:00
day d 当天 00:00
hour h 当前时间,0 分、0 秒、0 毫秒
minute m 当前时间,0 秒、0 毫秒
second s 当前时间,0 毫秒

Add()增加时间

// 增加七天
dayjs().add(7, 'day')
// 减去
dayjs().subtract(7, 'year')

subtract()减少时间

dayjs().subtract(1, 'day');

toDate()返回原生的时间对象

dayjs().toDate();

你可能感兴趣的:(nodejs,node.js)