JS-获取时间的方法:近3天,本周,本月,上月
作者:互联网
/** * 获取最近3天日期 * @param {*} day */ getDay: function (day) { var that = this; var today = new Date(); var targetday_milliseconds = today.getTime() + 1000 * 60 * 60 * 24 * day; today.setTime(targetday_milliseconds); //注意,这行是关键代码 var tYear = today.getFullYear(); var tMonth = today.getMonth(); var tDate = today.getDate(); tMonth = that.doHandleMonth(tMonth + 1); tDate = that.doHandleMonth(tDate); return tYear + "-" + tMonth + "-" + tDate; }, doHandleMonth: function (month) { var m = month; if (month.toString().length == 1) { m = "0" + month; } return m; }, /** * 获取本周起止日期 */ getMonday: function (type, dates) { var now = new Date(); var nowTime = now.getTime(); var day = now.getDay(); var longTime = 24 * 60 * 60 * 1000; var n = longTime * 7 * (dates || 0); if (type == "s") { var dd = nowTime - (day - 1) * longTime + n; }; if (type == "e") { var dd = nowTime + (7 - day) * longTime + n; }; dd = new Date(dd); var y = dd.getFullYear(); var m = dd.getMonth() + 1; var d = dd.getDate(); m = m < 10 ? "0" + m : m; d = d < 10 ? "0" + d : d; var day = y + "-" + m + "-" + d; return day; }, /** * 获取上月,本月 */ getMonth: function (type, months) { var d = new Date(); var year = d.getFullYear(); var month = d.getMonth() + 1; if (Math.abs(months) > 12) { months = months % 12; }; if (months != 0) { if (month + months > 12) { year++; month = (month + months) % 12; } else if (month + months < 1) { year--; month = 12 + month + months; } else { month = month + months; }; }; month = month < 10 ? "0" + month : month; var date = d.getDate(); var firstday = year + "-" + month + "-" + "01"; var lastday = ""; if (month == "01" || month == "03" || month == "05" || month == "07" || month == "08" || month == "10" || month == "12") { lastday = year + "-" + month + "-" + 31; } else if (month == "02") { if ((year % 4 == 0 && year % 100 != 0) || (year % 100 == 0 && year % 400 == 0)) { lastday = year + "-" + month + "-" + 29; } else { lastday = year + "-" + month + "-" + 28; }; } else { lastday = year + "-" + month + "-" + 30; }; var day = ""; if (type == "s") { day = firstday; } else { day = lastday; }; return day; },
调用的方法:
近3天:getDay(-3)
当天:getDay(0)
本周:开始时间:getMonday("s", 0) 结束时间:getMonday("e", 0)
上月:开始时间:getMonth("s", -1) 结束时间:getMonth("e", -1)
本月:开始时间:getMonth("s", 0) 结束时间:getMonth("e", 0)
标签:months,本月,month,获取,year,var,JS,day,getMonth 来源: https://www.cnblogs.com/liuqingxia/p/15438904.html