如何获取特定月份的天数?
问题描述:
在Dart语言中,如何获取特定月份的天数?
In the Dart language, how do I get the number of days in a specific month?
例如:
DateTime dateTime = DateTime(2017, 2, 1); //Feb 2017
例如,如何获得2017年2月的最大天数?
How do I get the maximum number of days in Feb 2017, for example?
我的问题是关于Dart语言的.
My question is about the Dart language.
答
您可以使用 date_utils 具有 lastDayOfMonth
方法的软件包.
You can use the date_utils package which has the lastDayOfMonth
method.
添加依赖项:
dev_dependencies:
date_utils: ^0.1.0
导入程序包:
import 'package:date_utils/date_utils.dart';
然后使用它:
final DateTime date = new DateTime(2017, 2);
final DateTime lastDay = Utils.lastDayOfMonth(date);
print("Last day in month : ${lastDay.day}");
结果:
一个月的最后一天:28
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));
}