当前位置: 首页 > 后端技术 > Node.js

moment的简单使用

时间:2023-04-03 15:29:05 Node.js

基本用法--获取时间点//获取当前时间moment().format("YYYY-MM-DDHH:mm:ss");//当前时间前10天的日期moment().subtract(10,"days").format("YYYY-MM-DD");//当前时间前一年moment().subtract(1,"年").format("YYYY-MM-DD");**//当前时间前3个月的时间**moment().subtract(3,"months").format("YYYY-MM-DD");//当前时间上一周的时间moment().subtract(1,"weeks").format("YYYY-MM-DD");获取时间范围//获取当前时间conststartDate=moment().format('YYYY-MM-DD');//获取本周开始和结束日期conststartDate=moment().week(moment().week()).startOf('week').format('YYYY-MM-DD');//年月日格式constendDate=moment().week(moment().week()).endOf('week').valueOf();//时间戳的格式//获取本月的起止日期conststartDate=moment().month(moment().month()).startOf('month').valueOf();constendDate=moment().month(moment().month()).endOf('month').valueOf();//获取conststartDate=moment().year(moment().year()).startOf('year').valueOf();constendDate=moment().year(moment().year()).endOf('year').valueOf();封装方法获取本周、前n周、后n周的起止日期(即周一和周日的日期)。封装工具类DateTime.js可以直接复制到项目中,使用/***timeanddatetoolclass*/importmomentfrom'moment'exportdefault{//获取本周周一周日日期getCurrentWeek(){conststart=moment().weekday(1).格式('YYYY-MM-DD');//这个星期一的日期constend=moment().weekday(7).format('YYYY-MM-DD');//本周日的日期return{start,end}},/***获取前i周的周一和周日日期*当i=1时,获取上周一和上周日的日期;*当i=2时,获取最后一个星期一和最后一个星期日的日期*...*@parami*/getLastWeek(i){constweekOfDay=parseInt(moment().format('E'));//计算今天是星期几constlast_monday=moment().subtract(weekOfDay+7*i-1,'days').format('YYYY-MM-DD');//星期一日期constlast_sunday=moment().subtract(weekOfDay+7*(i-1),'days').format('YYYY-MM-DD');//周日日期返回{last_monday,last_sunday}}/***获取周一和周日得到*后第i周的日期当i=1时,得到下周一和下周日的日期;*当i=2时,获取下周一和下周日的日期*...*@parami*/getNextWeek(i){constweekOfDay=parseInt(moment().format('E'));//计算今天是星期几constnext_monday=moment().add((7-weekOfDay)+7*(i-1)+1,'days').format('YYYY-MM-DD');//星期一日期constnext_sunday=moment().add((7-weekOfDay)+7*i,'days').format('YYYY-MM-DD');//周日日期return{next_monday,next_sunday}}}调用实例:constcurrentWeek1=DateTimeUtils.getCurrentWeek()//获取本周的开始和结束日期constcurrentWeek2=DateTimeUtils.getLastWeek(0)//获取开始和结束dateofthisweekconstcurrentWeek3=DateTimeUtils.getNextWeek(0)//获取本周的起止日期constlastWeek1=DateTimeUtils.getLastWeek(1)//获取上周的起止日期constlastWeek2=DateTimeUtils.getLastWeek(2)//获取上周的开始和结束日期constlastWeek3=DateTimeUtils.getLastWeek(3)//获取前三周的开始和结束日期constnextWeek1=DateTimeUtils.getNextWeek(1)//获取开始下周的起止日期constnextWeek2=DateTimeUtils.getNextWeek(2)//获取下一周的起止日期constnextWeek3=DateTimeUtils.getNextWeek(3)//获取下三周的起止日期