Home > Net >  how to get the month start and end minisecond in dart
how to get the month start and end minisecond in dart

Time:07-12

I want to using dart Dart SDK version: 2.17.3 (stable) (Wed Jun 1 11:06:41 2022 0200) on "macos_arm64" to get start and end minisecond of current month. I tried like this but I did not know how to get the last day 23:59:59:999 unix timestamp:

  endOfMonthMilliseconds(DateTime now) {
    var beginningNextMonth = (now.month < 12) ? new DateTime(now.year, now.month   1, 1) : new DateTime(now.year   1, 1, 1);
    var lastDay = beginningNextMonth.subtract(new Duration(days: 1)).millisecondsSinceEpoch;
  }

CodePudding user response:

I recommend using UTC dates, because then you won't get into daylight saving issues, but if you do the need local time end-of-month, this should work:

DateTime endOfMonth(DateTime now) {
  return DateTime(now.year, now.month   1, 1, 0, 0, 0, -1);
}

The DateTime constructor allows overflow and underflow between fields, so DateTime(now.year, now.month 1, 1) would give you the first of the following month (no need to do the December-to-January overflow yourself), and appending the , 0, 0, 0, -1 should give you one millisecond earlier than that.

  •  Tags:  
  • dart
  • Related