Ahmed Hammad
Ahmed Hammad

Reputation: 669

How to get the number of days in a specific month?

In the Dart language, how do I get the number of days in a specific month?

Ex:

DateTime dateTime = DateTime(2017, 2, 1); //Feb 2017

How do I get the maximum number of days in Feb 2017, for example?

My question is about the Dart language.

Upvotes: 9

Views: 8151

Answers (5)

JM Apps
JM Apps

Reputation: 180

Returns the number of days in a month, according to the proleptic Gregorian calendar. This applies the leap year logic introduced by the Gregorian reforms of It will not give valid results for dates prior to that time. Official documentation

static int getDaysInMonth(int year, int month) {
if (month == DateTime.february) {
  final bool isLeapYear = (year % 4 == 0) && (year % 100 != 0) || (year % 400 == 0);
  return isLeapYear ? 29 : 28;
}
const List<int> daysInMonth = <int>[31, -1, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31];
return daysInMonth[month - 1];
}

Upvotes: 0

Deepanshu
Deepanshu

Reputation: 1120

The below method I belief is correct and avoids edge cases from things like DST.

1. First get the start and end date of a month which can be achieved by these functions:-

As month always starts from 1 we can find start date like this:

DateTime firstDayOfMonth = DateTime(currentDateTime.year, currentDateTime.month, 1);

Now, getting the last day is a little bit different and can be done like this:

DateTime getLastDayOfAMonth({required DateTime currentDateTime}) {
  // Getting the 15th-day date of the month for the date provided
  DateTime fifteenthDayOfMonth =
      DateTime(currentDateTime.year, currentDateTime.month, 15);

  // Converting the 15th-day date to UTC
  // So that all things like DST don't affect subtraction and addition on date
  DateTime twentiethDayOfMonthInUTC = fifteenthDayOfMonth.toUtc();

  // Getting a random date of next month by adding 20 days to twentiethDayOfMonthInUTC
  // Adding number 20 to any month 15th-day will definitely give a next month date
  DateTime nextMonthRandomDateInUTC =
      twentiethDayOfMonthInUTC.add(const Duration(days: 20));

  DateTime nextMonthRandomDateZeroDayInUTC = DateTime.utc(
      nextMonthRandomDateInUTC.year, nextMonthRandomDateInUTC.month, 0);

  // Now getting the 0th day date of the next month
  // This will give us the current month last date
  DateTime nextMonthRandomDateZeroDayInLocal = DateTime(
      nextMonthRandomDateInUTC.year, nextMonthRandomDateInUTC.month, 0);

  DateTime lastDayOfAMonth;
  if (currentDateTime.isUtc) {
    lastDayOfAMonth = nextMonthRandomDateZeroDayInUTC;
  } else {
    lastDayOfAMonth = nextMonthRandomDateZeroDayInLocal;
  }

  return lastDayOfAMonth;
}

2. Get the dates between the start and end date calculated in step 1 above.

Now we will find the dates between two dates like this:

List<DateTime> getDaysInBetweenIncludingStartEndDate(
    {required DateTime startDateTime, required DateTime endDateTime}) {
  // Converting dates provided to UTC
  // So that all things like DST don't affect subtraction and addition on dates
  DateTime startDateInUTC =
      DateTime.utc(startDateTime.year, startDateTime.month, startDateTime.day);
  DateTime endDateInUTC =
      DateTime.utc(endDateTime.year, endDateTime.month, endDateTime.day);

  // Created a list to hold all dates
  List<DateTime> daysInFormat = [];

  // Starting a loop with the initial value as the Start Date
  // With an increment of 1 day on each loop
  // With condition current value of loop is smaller than or same as end date
  for (DateTime i = startDateInUTC;
      i.isBefore(endDateInUTC) || i.isAtSameMomentAs(endDateInUTC);
      i = i.add(const Duration(days: 1))) {
    // Converting back UTC date to Local date if it was local before
    // Or keeping in UTC format if it was UTC

    if (startDateTime.isUtc) {
      daysInFormat.add(i);
    } else {
      daysInFormat.add(DateTime(i.year, i.month, i.day));
    }
  }
  return daysInFormat;
}

3. Now, use the list provided in step 2 and calculate its length to find the number of dates in the month for the provided date.

Upvotes: 0

rubStackOverflow
rubStackOverflow

Reputation: 6163

void main() {
  DateTime now = new DateTime.now();
  DateTime lastDayOfMonth = new DateTime(now.year, now.month+1, 0);
  print("N days: ${lastDayOfMonth.day}");
}

Source

Upvotes: 17

A. L. Strine
A. L. Strine

Reputation: 651

As of October 2019, date_utils hasn't been updated for a year and has errors. Instead try the package calendarro, it's being updated regularly and has what you're looking for.

Follow the instructions in the link above for installation. Implementation looks like this:

DateTime lastDayOfMonth = DateUtils.getLastDayOfMonth(DateTime(fooYear, barMonth));
int lastDayOfMonthAsInt = lastDayOfMonth.day;

To do it yourself:

int daysIn({int month, int forYear}){
  DateTime firstOfNextMonth;
  if(month == 12) {
    firstOfNextMonth = DateTime(forYear+1, 1, 1, 12);//year, month, day, hour
  }
  else {
    firstOfNextMonth = DateTime(forYear, month+1, 1, 12);
  }
  int numberOfDaysInMonth = firstOfNextMonth.subtract(Duration(days: 1)).day;
  //.subtract(Duration) returns a DateTime, .day gets the integer for the day of that DateTime
  return numberOfDaysInMonth;
}

Modify as needed if you want the datetime instead.

Upvotes: 3

Yann39
Yann39

Reputation: 15699

You can use the date_utils package which has the lastDayOfMonth method.

Add dependency :

dev_dependencies:
    date_utils: ^0.1.0

Import package :

import 'package:date_utils/date_utils.dart';

Then use it :

final DateTime date = new DateTime(2017, 2);
final DateTime lastDay = Utils.lastDayOfMonth(date);
print("Last day in month : ${lastDay.day}");

Result :

Last day in month : 28

If you don't want to include the package just for that function, here is the definition :

/// The last day of a given month
static DateTime lastDayOfMonth(DateTime month) {
  var beginningNextMonth = (month.month < 12)
      ? new DateTime(month.year, month.month + 1, 1)
      : new DateTime(month.year + 1, 1, 1);
  return beginningNextMonth.subtract(new Duration(days: 1));
}

Upvotes: 10

Related Questions