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.
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));
}
void main() {
DateTime now = new DateTime.now();
DateTime lastDayOfMonth = new DateTime(now.year, now.month+1, 0);
print("N days: ${lastDayOfMonth.day}");
}
Source
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With