js获取指定时间
moment.js格式化日期
获取当前日期:
moment(new Date()).format("YYYY-MM-DD")
获取指定年份第一天和最后一天:
moment(new Date('2019')).startOf('year').format("YYYY-MM-DD")
moment(new Date(data)).endOf('year').format("YYYY-MM-DD")
当年第一天和最后一天
moment().year(moment().year()).startOf('year').format('YYYY-MM-DD')
moment().year(moment().year()).endOf('year').format('YYYY-MM-DD')
指定月份第一天和最后一天
moment(new Date('2019-5')).startOf('month').format("YYYY-MM-DD")
moment(new Date('2019-5')).endOf('month').format("YYYY-MM-DD")
当月第一天和最后一天
moment(new Date()).startOf("month").format("YYYY-MM-DD"),
moment(new Date()).endOf("month").format("YYYY-MM-DD")
1. 获取上周一和上周日的日期
var myDate = new Date(); var weekDate = new Date(myDate.getTime() - 7 * 24 * 3600 * 1000);// 计算开始时间用 var weekDate2 = new Date(myDate.getTime() - 7 * 24 * 3600 * 1000);// 计算结束时间用 var day = weekDate.getDay(); var time = weekDate.getDate()-day+(day===0?-6:1); var startDate = new Date(weekDate.setDate(time)); var beginTime = startDate.getFullYear()+'-'+(startDate.getMonth()+1)+'-'+startDate.getDate(); var endDate = new Date(weekDate2.setDate(time+6)); var endTime = endDate.getFullYear()+'-'+(endDate.getMonth()+1)+'-'+endDate.getDate();
2. 获取今天之前一周日期
// var currDate = new Date(); // var year = currDate.getFullYear(); // var month = currDate.getMonth(); // var day = currDate.getDate(); // var oneweekdate = new Date(new Date()-7*24*3600*1000); // var y = oneweekdate.getFullYear(); // var m = oneweekdate.getMonth()+1; // var d = oneweekdate.getDate(); // var formatwdate = y+'-'+m+'-'+d;
3. 根据element-ui类型为月的日期选择插件获取指定月的第一天与最后一天
var beginDay = data+'-01' //第一天 var endDate = new Date(data); var month=endDate.getMonth(); var nextMonth=++month; var nextMonthFirstDay=new Date(endDate.getFullYear(),nextMonth,1); var oneDay=1000*60*60*24; var lastYear = new Date(nextMonthFirstDay-oneDay).getFullYear() var lastMonth = new Date(nextMonthFirstDay-oneDay).getMonth() + 1 var lastDay = new Date(nextMonthFirstDay-oneDay).getDate() var lastTime = lastYear+'-'+lastMonth+'-'+lastDay
4. 获取上个月的第一天与最后一天
var nowdays = new Date(); var year = nowdays.getFullYear(); var month = nowdays.getMonth(); if(month==0){ month = 12; year = year-1; } if(month<10){ month = '0'+month; } var myDate = new Date(year,month,0); var startDate = year+'-'+month+'-01 '; //上个月第一天 var endDate = year+'-'+month+'-'+myDate.getDate();//上个月最后一天