How to get Last Day of a Week, month, and year in Dart| Flutter by Example
This tutorial shows you multiple ways to get the Last Day of a Month and Year in Dart and Flutter.
How to get the Last Day of a month in Dart and Flutter
The first way, Using Datetime.day
property
Construct the DateTime object using the constructor with month always considered as value -1.
For example, Object using DateTime(2013, 3, 0); created with Feb 2013 data.
void main() {
DateTime now = DateTime.now(); // March 2022
var date = new DateTime(now.year, now.month + 1, 0);
print(date.day); // 30
var date1 = new DateTime(2013, 3, 0); // Feb 2013
print(date1.day); // 28
}
Output:
30
28
The second way is using the jiffy
library
jiffy is a dart dependency library that contains date and time utilities Add the dependency to pubspec.yaml
dependencies:
jiffy: ^5.0.0
install the dependency using the dart pub update command
Jiffy() returns the current date endOf method returns the end date using Units provided,. Units is an Enum class for MILLISECOND, SECOND, MINUTE, HOUR, DAY, WEEK, MONTH, YEAR
Jiffy endOf(Units units)
Here is a program
import 'package:jiffy/jiffy.dart';
void main() {
var lastDay = Jiffy().endOf(Units.MONTH);
var lastDay1 = Jiffy("2022-02-01").endOf(Units.MONTH);
print(lastDay.dateTime);
print(lastDay1.dateTime);
}
Output:
2022-04-30 23:59:59.999
2023-05-01 23:59:59.999
How to get Last Day of a Year in Dart/Flutter
Jiffy().endOf(Units.YEAR) returns the last date of an year.
import 'package:jiffy/jiffy.dart';
void main() {
var lastDay = Jiffy().endOf(Units.YEAR);
var lastDay1 = Jiffy("2022-02-01").endOf(Units.YEAR);
print(lastDay.dateTime);
print(lastDay1.dateTime);
}
Output:
2023-05-01 23:59:59.999
2023-05-01 23:59:59.999
How to get the Last Day of a Current Week in Dart/Flutter
Jiffy().endOf(Units.WEEK) returns last day of an current week.
import 'package:jiffy/jiffy.dart';
void main() {
var lastDay = Jiffy().endOf(Units.WEEK);
var lastDay1 = Jiffy("2022-02-01").endOf(Units.WEEK);
print(lastDay.dateTime);
print(lastDay1.dateTime);
}
Output
2022-10-30 23:59:59.999
2022-02-05 23:59:59.999
Conclusion
To summarize,
Examples for returning on the last day of the Week, Month, or Year of a given date.