jquery 如何在JavaScript中获取每个月的指定日期?

57hvy0tb  于 2023-10-17  发布在  jQuery
关注(0)|答案(7)|浏览(137)

我需要找到这个月,上个月和下个月的具体日期。
例如,日期被设置为每月的31,我希望得到的日期是2018-02-28,2018-03-31和2018-04-30。对于那些没有31的日期,比它成为前一天。
最后生成2期,2018-02-28至2018-03-29,2018-03-30至2018-04-31。我不知道如何处理二月和不到31的月份。

  1. var d = new Date();
  2. var tyear = d.getFullYear(); //2018
  3. var tmonth = d.getMonth(); //2
  4. new Date(2018, tmonth-1, 31);//output 2018-03-02 not what I wanted
cbjzeqam

cbjzeqam1#

一个简单的算法是将月份添加到原始日期,如果新日期错误,则将其设置为前一个月的最后一天。保持原始日期值不变会有所帮助,例如:

  1. /* @param {Date} start - date to start
  2. ** @param {number} count - number of months to generate dates for
  3. ** @returns {Array} monthly Dates from start for count months
  4. */
  5. function getMonthlyDates(start, count) {
  6. var result = [];
  7. var temp;
  8. var year = start.getFullYear();
  9. var month = start.getMonth();
  10. var startDay = start.getDate();
  11. for (var i=0; i<count; i++) {
  12. temp = new Date(year, month + i, startDay);
  13. if (temp.getDate() != startDay) temp.setDate(0);
  14. result.push(temp);
  15. }
  16. return result;
  17. }
  18. // Start on 31 Jan in leap year
  19. getMonthlyDates(new Date(2016,0,31), 4).forEach(d => console.log(d.toString()));
  20. // Start on 31 Jan not in leap year
  21. getMonthlyDates(new Date(2018,0,31), 4).forEach(d => console.log(d.toString()));
  22. // Start on 30 Jan
  23. getMonthlyDates(new Date(2018,0,30), 4).forEach(d => console.log(d.toString()));
  24. // Start on 5 Jan
  25. getMonthlyDates(new Date(2018,0,5), 4).forEach(d => console.log(d.toString()));
展开查看全部
tyky79it

tyky79it2#

我想你需要一个有12个数字的数组。每个数字是每个月的天数,数组中的数字按顺序排列(第一个数字是31,因为1月有31天,第二个数字是28或29,代表2月)。然后,您将从输入的日期中获取月份号,并在数组中查找与月份号+/- 1对应的数字。
然后,您需要根据当前月份的天数构建上个月和下个月的日期。
见内联评论:

  1. let daysInMonths = [31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31];
  2. document.getElementById("date").addEventListener("input", function(){
  3. console.clear();
  4. // Create new Date based on value in date picker
  5. var selectedDate = new Date(this.value + 'T00:00');
  6. var year = selectedDate.getYear();
  7. // Determine if it is a leap year (Feb has 29 days) and update array if so.
  8. if (((year % 4 === 0) && (year % 100 !== 0)) || (year % 400 === 0)) {
  9. daysInMonths[1] = 29;
  10. }
  11. var selectedDateMonth = selectedDate.getMonth();
  12. // Get previous month number (if current month is January, get December)
  13. let prevMonth = selectedDateMonth > 0 ? selectedDateMonth - 1 : 11;
  14. let prevMonthDate = null;
  15. // If selected date is last day of month...
  16. if(selectedDate.getDate() === daysInMonths[selectedDateMonth]){
  17. // Create new date that takes the selected date and subtracts the correct amount of
  18. // days from it based on a lookup in the array.
  19. var newDate1 = new Date(selectedDate.getTime());
  20. prevMonthDate =
  21. new Date(newDate1.setDate(selectedDate.getDate() - daysInMonths[selectedDateMonth]));
  22. } else {
  23. // Create a new date that is last month and one day earlier
  24. var newDate2 = new Date(selectedDate.getTime());
  25. prevMonthDate =
  26. new Date(new Date(newDate2.setDate(selectedDate.getDate() - 1))
  27. .setMonth(selectedDate.getMonth() - 1));
  28. }
  29. // Get next month (if current month is December, get January
  30. let nextMonth = selectedDateMonth < 11 ? selectedDateMonth + 1 : 0;
  31. let nextMonthDate = null;
  32. // Same idea for next month, but add instead of subtract.
  33. // If selected date is last day of month...
  34. if(selectedDate.getDate() === daysInMonths[selectedDateMonth]){
  35. var newDate3 = new Date(selectedDate.getTime());
  36. nextMonthDate =
  37. new Date(newDate3.setDate(selectedDate.getDate() + daysInMonths[selectedDateMonth + 1]));
  38. } else {
  39. var newDate4 = new Date(selectedDate.getTime());
  40. nextMonthDate = new Date(new Date(newDate4.setDate(selectedDate.getDate() + 1)).setMonth(selectedDate.getMonth() + 1));
  41. }
  42. console.log("Last month date: " + prevMonthDate.toLocaleDateString());
  43. console.log("Next month date: " + nextMonthDate.toLocaleDateString());
  44. });
  1. <p>Pick a date: <input type="date" id="date"></p>
展开查看全部
idv4meu8

idv4meu83#

使用此方法:

Javascript Date Object – Adding and Subtracting Months

作者

在尝试前进到下一个月或返回到前一个月时,JavaScript Date()对象有一个小问题。
例如,如果您的日期设置为2018年10月31日,并添加一个月,则您可能会期望新日期为2018年11月30日,因为11月31日不存在。然而,事实并非如此。
JavaScript会自动将Date对象提前到12月1日。此功能在大多数情况下都非常有用(即,在日期上加上天数,确定一个月的天数或是否是闰年),但不适用于加/减月份。下面我整理了一些扩展Date()对象的函数:nextMonth()prevMonth()

  1. function prevMonth() {
  2. var thisMonth = this.getMonth();
  3. this.setMonth(thisMonth - 1);
  4. if (this.getMonth() != thisMonth - 1 && (this.getMonth() != 11 || (thisMonth == 11 && this.getDate() == 1)))
  5. this.setDate(0);
  6. }
  7. function nextMonth() {
  8. var thisMonth = this.getMonth();
  9. this.setMonth(thisMonth + 1);
  10. if (this.getMonth() != thisMonth + 1 && this.getMonth() != 0)
  11. this.setDate(0);
  12. }
  13. Date.prototype.nextMonth = nextMonth;
  14. Date.prototype.prevMonth = prevMonth;
  15. var today = new Date(2018, 2, 31); //<----- March 31st, 2018
  16. var prevMonth = new Date(today.getTime());
  17. prevMonth.prevMonth();
  18. console.log("Previous month:", prevMonth);
  19. console.log("This month:", today)
  20. var nextMonth = new Date(today.getTime());
  21. nextMonth.nextMonth();
  22. console.log("Next month:", nextMonth);
  1. .as-console-wrapper { max-height: 100% !important; top: 0; }
展开查看全部
qij5mzcb

qij5mzcb4#

日期和时区在JS中是一个真实的痛苦,所以接受挑战。
我把它分解成两个步骤:

  • 算算上个月和下个月的日子
  • 与所选日期进行比较并选择最低数字
    包括的测试用例
  1. function createUTCDate(year, month, day) {
  2. return new Date(Date.UTC(year, month, day));
  3. }
  4. function splitDate(date) {
  5. return {
  6. year: date.getUTCFullYear(),
  7. month: date.getUTCMonth(),
  8. day: date.getUTCDate()
  9. };
  10. }
  11. function numberOfDaysInMonth(year, month) {
  12. return new Date(year, month + 1, 0).getDate();
  13. }
  14. function dateNextMonth(dateObj) {
  15. const daysNextMonth = numberOfDaysInMonth(dateObj.year, dateObj.month + 1);
  16. const day = Math.min(daysNextMonth, dateObj.day);
  17. return createUTCDate(dateObj.year, dateObj.month + 1, day);
  18. }
  19. function datePreviousMonth(dateObj) {
  20. const daysPrevMonth = numberOfDaysInMonth(dateObj.year, dateObj.month - 1);
  21. const day = Math.min(daysPrevMonth, dateObj.day);
  22. return createUTCDate(dateObj.year, dateObj.month - 1, day);
  23. }
  24. const log = console.log;
  25. function print(dateString) {
  26. const date = new Date(dateString);
  27. const dateObj = splitDate(date);
  28. log("Previous: ", datePreviousMonth(dateObj).toISOString());
  29. log("Selected: ", date.toISOString());
  30. log("Next: ", dateNextMonth(dateObj).toISOString());
  31. log("--------------");
  32. }
  33. const testCases = [
  34. "2018-03-01 UTC",
  35. "2018-03-31 UTC",
  36. "2018-01-01 UTC",
  37. "2018-12-31 UTC"
  38. ];
  39. testCases.forEach(print);

请注意,黑客与new Date(xxx + " UTC")是不符合规格,只是有测试的目的.结果可能因浏览器而异。您应该选择一种输入格式并相应地构建日期。

展开查看全部
6tr1vspr

6tr1vspr5#

我用一种愚蠢的方式处理它,

  1. let daysInMonths = [31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31];
  2. let months = ["01", "02", "03", "04", "05", "06", "07", "08", "09", "10", "11", "12"];
  3. var target = nexttarget = lasttarget = "29"; //target day
  4. if (((year % 4 === 0) && (year % 100 !== 0)) || (year % 400 === 0)) {
  5. daysInMonths[1] = 29;
  6. }
  7. function findLastDay(target, month){
  8. if(target > daysInMonths[month]){
  9. target = daysInMonths[month];
  10. }
  11. return target;
  12. }

然后

  1. var d = new Date();
  2. var year = d.getFullYear();
  3. var month = d.getMonth();
  4. target = findLastDay(target, month);
  5. var this_month = year+"-"+months[month]+"-"+target;
  6. console.log(this_month);//2018-03-29
  7. // next month
  8. if(month == 11){
  9. nextmonth = 0;
  10. nextyear = year + 1;
  11. }else{
  12. nextmonth = month+1;
  13. nextyear = year;
  14. }
  15. nexttarget = findLastDay(nexttarget, nextmonth);
  16. var next_month = nextyear+"-"+months[nextmonth]+"-"+nexttarget;
  17. console.log(next_month);//2018-04-29
  18. //last month
  19. if(month == 0){
  20. lastmonth = 11;
  21. lastyear = year - 1;
  22. }else{
  23. lastmonth = month - 1;
  24. lastyear = year;
  25. }
  26. lasttarget = findLastDay(lasttarget, lastmonth);
  27. var last_month = lastyear+"-"+months[lastmonth]+"-"+lasttarget;
  28. console.log(last_month);//2018-02-28
展开查看全部
gopyfrb3

gopyfrb36#

  1. var d = new Date();
  2. var tyear = d.getFullYear(); //2018
  3. var tmonth = d.getMonth(); //2
  4. var currDate = new Date(tyear, tmonth, "31");

我希望这会有所帮助。它对我很有效

x4shl7ld

x4shl7ld7#

即使在最好的情况下,处理日期也是很棘手的。别自己动手使用Moment.js

  1. var target = 31;
  2. var today = moment().date(target).calendar();
  3. // today == '03/31/2018'
  4. var nextMonth = moment().date(target).add(1, 'month').calendar();
  5. // nextMonth == '04/30/2018'
  6. var lastMonth = moment().date(target).subtract(1, 'month').calendar()
  7. // lastMonth == '02/28/2018'

相关问题