UNPKG

web-utils-super

Version:

前端函数库

52 lines (46 loc) 1.5 kB
const formatTime = require('./formatTime') /** * @desc: 获取某月起止时间 * @param {Date | String} 年月日 '2022-2-2' | '2022/2/2' | '2022.2.2' | 不传默认是当天 * @return {Array} */ function getCurrentMonth(time) { // 起止日期数组 let startStop = new Array() // 获取当前时间 let currentDate = time ? new Date(time) : new Date() // 获得当前月份0-11 let currentMonth = currentDate.getMonth() // 获得当前年份4位年 let currentYear = currentDate.getFullYear() // 求出本月第一天 let firstDay = new Date(currentYear, currentMonth, 1) // 当为12月的时候年份需要加1 // 月份需要更新为0 也就是下一年的第一个月 if (currentMonth == 11) { currentYear++ currentMonth = 0 // 就为 } else { // 否则只是月份增加,以便求的下一月的第一天 currentMonth++ } // 第一天 let nextMonthDayOne = new Date(currentYear, currentMonth, 1) // 最后一天 let lastDay = new Date(nextMonthDayOne.getTime()) firstDay.setHours(0) firstDay.setMinutes(0) firstDay.setSeconds(0) firstDay.setMilliseconds(0) lastDay.setHours(0) lastDay.setMinutes(0) lastDay.setSeconds(0) lastDay.setMilliseconds(0) lastDay = new Date(lastDay.getTime() - 1) // 添加至数组中返回 startStop.push(formatTime(firstDay)) startStop.push(formatTime(lastDay)) // 返回 return startStop } module.exports = getCurrentMonth