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

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

我需要找到这个月,上个月和下个月的具体日期。
例如,日期被设置为每月的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的月份。

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

cbjzeqam1#

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

/* @param {Date} start - date to start
** @param {number} count - number of months to generate dates for
** @returns {Array} monthly Dates from start for count months
*/
function getMonthlyDates(start, count) {
  var result = [];
  var temp;
  var year = start.getFullYear();
  var month = start.getMonth();
  var startDay = start.getDate();
  for (var i=0; i<count; i++) {
    temp = new Date(year, month + i, startDay);
    if (temp.getDate() != startDay) temp.setDate(0);
    result.push(temp);
  }
  return result;
}

// Start on 31 Jan in leap year
getMonthlyDates(new Date(2016,0,31), 4).forEach(d => console.log(d.toString()));
// Start on 31 Jan not in leap year
getMonthlyDates(new Date(2018,0,31), 4).forEach(d => console.log(d.toString()));

// Start on 30 Jan
getMonthlyDates(new Date(2018,0,30), 4).forEach(d => console.log(d.toString()));
// Start on 5 Jan
getMonthlyDates(new Date(2018,0,5), 4).forEach(d => console.log(d.toString()));
tyky79it

tyky79it2#

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

let daysInMonths = [31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31];

document.getElementById("date").addEventListener("input", function(){
  console.clear();
  
  // Create new Date based on value in date picker
  var selectedDate = new Date(this.value + 'T00:00');

  var year = selectedDate.getYear();

  // Determine if it is a leap year (Feb has 29 days) and update array if so.
  if (((year % 4 === 0) && (year % 100 !== 0)) || (year % 400 === 0)) {
    daysInMonths[1] = 29;
  }

  var selectedDateMonth = selectedDate.getMonth();
     
  // Get previous month number (if current month is January, get December)
  let prevMonth = selectedDateMonth > 0 ? selectedDateMonth - 1 : 11;
  
  let prevMonthDate = null;
  
  // If selected date is last day of month...
  if(selectedDate.getDate() === daysInMonths[selectedDateMonth]){
    // Create new date that takes the selected date and subtracts the correct amount of
    // days from it based on a lookup in the array.
    var newDate1 = new Date(selectedDate.getTime());
    prevMonthDate = 
     new Date(newDate1.setDate(selectedDate.getDate() - daysInMonths[selectedDateMonth]));
  } else {
    // Create a new date that is last month and one day earlier
    var newDate2 = new Date(selectedDate.getTime());
    prevMonthDate = 
      new Date(new Date(newDate2.setDate(selectedDate.getDate() - 1))
        .setMonth(selectedDate.getMonth() - 1));
  }
  
  // Get next month (if current month is December, get January
  let nextMonth = selectedDateMonth < 11 ? selectedDateMonth + 1 : 0;  
  
  let nextMonthDate = null;
  
  // Same idea for next month, but add instead of subtract.
  
  // If selected date is last day of month...
  if(selectedDate.getDate() === daysInMonths[selectedDateMonth]){
    var newDate3 = new Date(selectedDate.getTime());
    nextMonthDate = 
     new Date(newDate3.setDate(selectedDate.getDate() + daysInMonths[selectedDateMonth + 1]));
  } else {
    var newDate4 = new Date(selectedDate.getTime());
    nextMonthDate = new Date(new Date(newDate4.setDate(selectedDate.getDate() + 1)).setMonth(selectedDate.getMonth() + 1));
  }  

  console.log("Last month date: " + prevMonthDate.toLocaleDateString());
  console.log("Next month date: " + nextMonthDate.toLocaleDateString());  
});
<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()

function prevMonth() {
  var thisMonth = this.getMonth();
  this.setMonth(thisMonth - 1);
  if (this.getMonth() != thisMonth - 1 && (this.getMonth() != 11 || (thisMonth == 11 && this.getDate() == 1)))
    this.setDate(0);
}

function nextMonth() {
  var thisMonth = this.getMonth();
  this.setMonth(thisMonth + 1);
  if (this.getMonth() != thisMonth + 1 && this.getMonth() != 0)
    this.setDate(0);
}

Date.prototype.nextMonth = nextMonth;
Date.prototype.prevMonth = prevMonth;

var today = new Date(2018, 2, 31); //<----- March 31st, 2018

var prevMonth = new Date(today.getTime());
prevMonth.prevMonth();
console.log("Previous month:", prevMonth);

console.log("This month:", today)

var nextMonth = new Date(today.getTime());
nextMonth.nextMonth();
console.log("Next month:", nextMonth);
.as-console-wrapper { max-height: 100% !important; top: 0; }
qij5mzcb

qij5mzcb4#

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

  • 算算上个月和下个月的日子
  • 与所选日期进行比较并选择最低数字
    包括的测试用例
function createUTCDate(year, month, day) {
  return new Date(Date.UTC(year, month, day));
}

function splitDate(date) {
  return {
    year: date.getUTCFullYear(),
    month: date.getUTCMonth(),
    day: date.getUTCDate()
  };
}

function numberOfDaysInMonth(year, month) {
  return new Date(year, month + 1, 0).getDate();
}

function dateNextMonth(dateObj) {
  const daysNextMonth = numberOfDaysInMonth(dateObj.year, dateObj.month + 1);
  const day = Math.min(daysNextMonth, dateObj.day);
  return createUTCDate(dateObj.year, dateObj.month + 1, day);
}

function datePreviousMonth(dateObj) {
  const daysPrevMonth = numberOfDaysInMonth(dateObj.year, dateObj.month - 1);
  const day = Math.min(daysPrevMonth, dateObj.day);
  return createUTCDate(dateObj.year, dateObj.month - 1, day);
}

const log = console.log;

function print(dateString) {
  const date = new Date(dateString);
  const dateObj = splitDate(date);
  log("Previous: ", datePreviousMonth(dateObj).toISOString());
  log("Selected: ", date.toISOString());
  log("Next: ", dateNextMonth(dateObj).toISOString());
  log("--------------");
}

const testCases = [
  "2018-03-01 UTC",
  "2018-03-31 UTC",
  "2018-01-01 UTC",
  "2018-12-31 UTC"
];

testCases.forEach(print);

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

6tr1vspr

6tr1vspr5#

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

let daysInMonths = [31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31];
let months = ["01", "02", "03", "04", "05", "06", "07", "08", "09", "10", "11", "12"];

var target = nexttarget = lasttarget = "29"; //target day

if (((year % 4 === 0) && (year % 100 !== 0)) || (year % 400 === 0)) {
    daysInMonths[1] = 29;
}

function findLastDay(target, month){
    if(target > daysInMonths[month]){
        target = daysInMonths[month];
    }
    return target;
}

然后

var d = new Date();
var year = d.getFullYear();
var month = d.getMonth();

target = findLastDay(target, month);

var this_month = year+"-"+months[month]+"-"+target;
console.log(this_month);//2018-03-29

// next month
if(month == 11){
   nextmonth = 0;
   nextyear = year + 1;
}else{
   nextmonth = month+1;
   nextyear = year;
}

nexttarget = findLastDay(nexttarget, nextmonth);

var next_month = nextyear+"-"+months[nextmonth]+"-"+nexttarget;
console.log(next_month);//2018-04-29

//last month
if(month == 0){
   lastmonth = 11;
   lastyear = year - 1;
}else{
   lastmonth = month - 1;
   lastyear = year;
}

lasttarget = findLastDay(lasttarget, lastmonth);

var last_month = lastyear+"-"+months[lastmonth]+"-"+lasttarget;
console.log(last_month);//2018-02-28
gopyfrb3

gopyfrb36#

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

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

x4shl7ld

x4shl7ld7#

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

var target = 31;
var today = moment().date(target).calendar();
//  today == '03/31/2018'

var nextMonth =  moment().date(target).add(1, 'month').calendar();
// nextMonth == '04/30/2018'

var lastMonth = moment().date(target).subtract(1, 'month').calendar()
// lastMonth == '02/28/2018'

相关问题