setDate() set the wrong date on 31st?

后端 未结 4 1820
刺人心
刺人心 2021-01-15 04:12

This is very weird I don\'t know what I\'m doing wrong. I have a function to grab the date (i.e in this format: 06/24/2011), here\'s the function:



        
4条回答
  •  野的像风
    2021-01-15 04:56

    You need to set the month before setting the day (or as Marc B points out in his comment, use the Date(yearval, monthval, dayval) constructor).

    When you create a Date object, it defaults to the current date. At the time of writing that's in June, so when you try to set the day to 31 it wraps.

    ...And because of similar behaviour in leap years, you should set the year before setting the month or day.

    (It's a good job you developed this code in June rather than in July - the bug would have lurked undiscovered until September, and it would probably have been your users that found it rather than you. :-)

提交回复
热议问题