0

Small question :

I calculate the number of days in a given month like so :

new DateTime(2018, month+1, 1).difference(new DateTime(2018,month,1)).inDays

All is working fine, februari gives me 28 days, all months are correctly 30/31 days except for March, which gives me 30 days instead of 31.

Has anyone seen this before and perhaps an explanation?

Thanks.

John Gorter
  • 2,162
  • 2
  • 17
  • 25

1 Answers1

2

I believe it's because of daylight-saving, try new DateTime.utc(), the below code outputs the correct values

for(int month = 1; month < 13; month++) {

  int daysInMonth = new DateTime.utc(2018, month+1,1).difference(new DateTime.utc(2018,month,1)).inDays;

  print(daysInMonth);
}

"When dealing with dates or historic events prefer to use UTC DateTimes, since they are unaffected by daylight-saving changes and are unaffected by the local timezone."

Rob Castillo
  • 171
  • 2
  • 6