0

I expect 31 because this month October has 31 days, which part of my code is wrong here?

function lastDayOfMonth(given_month) {
  var d = new Date();
  d.setDate(0);
  d.setMonth(given_month);
  return d.toISOString();
}

console.log(lastDayOfMonth(given_month))

2016-10-30T13:16:14.227Z

Edward Comeau
  • 3,874
  • 2
  • 21
  • 24
Jenny Mok
  • 2,744
  • 9
  • 27
  • 58

3 Answers3

1
d.setDate(0);

sets the date to the last day of the previous month. I.e if you run this script in October, the date will be set to Sep 30.

Afterwards you run

d.setMonth(given_month);

This sets the month, but leaves the day of month as it is. I assume that given_month is 9 (i.e. Oct), so this will result in Oct 30.

See https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_Objects/Date/setDate for more info.

sb9
  • 1,082
  • 7
  • 18
  • given_month value is 9, which means Oct. But isn't Oct has 31 days? – Jenny Mok Oct 31 '16 at 13:47
  • `var d = new Date();` creates a new date object with current date/time. `d.setDate(0);` sets the date to the last day of the previous month, i.e. to Sep 30. `d.setMonth(given_month);` sets the month to Oct, but doesn't change the day of month, ie this is still 30. So your resulting date is Oct 30. – sb9 Oct 31 '16 at 13:57
  • I still don't get it. My current date now is Oct 30. Please tell me why last day of the month of Oct is 30. – Jenny Mok Oct 31 '16 at 14:02
  • Because `d.setDate(0)` changes to the last day of the _previous_ month. If you still don't get it you should debug your function step by step, examining how your date object changes after each statement. – sb9 Oct 31 '16 at 14:05
  • so what should I do now? I just want to get the last day of a month, given given_month is a variable. – Jenny Mok Oct 31 '16 at 14:08
  • 1. For example `d.setMonth(given_month + 1); d.setDate(0);`. 2. Examine what happens in December with that code. 3. Read a book about how to learn programming – sb9 Oct 31 '16 at 14:10
  • Use `d.setMonth(given_month + 1, 0);`. This will work. Updated fiddle https://jsfiddle.net/hvn7kjso/1/ – sb9 Oct 31 '16 at 14:19
1
given_month = 10;

function lastDayOfMonth(given_month) {
  var d = new Date();
  d.setDate(15);
  d.setMonth(given_month);
  d.setDate(0)
  return d.toISOString();
}

console.log(lastDayOfMonth(given_month)) // 2016-10-30T13:16:14.227Z

Expl: Today is 31, so, new Date set day to 31; when you set month to 10 (November), day is still 31, but November only has 30 days, hence the error.

sergio0983
  • 1,232
  • 8
  • 15
  • Expl. added; note that 15 could be any number below 30 – sergio0983 Oct 31 '16 at 13:49
  • how to get current month but last day? like 31 Oct 2016? I passed given_month as 9. I get the month right but not the last day, it suppose to be 31 not 30. What should I do – Jenny Mok Oct 31 '16 at 14:10
0

setDate(0) will yield the last day of the previous month

Serg M Ten
  • 5,568
  • 4
  • 25
  • 48