How to get the name of the days of the week in Dart| Flutter by Example
DateTime.weekday
returns an integer number from 1 to 7, Monday
represents 1
, and Sunday
represents 7
.
void main() {
DateTime date = DateTime.now();
print(date); //2022-04-10 20:48:56.354 and Sunday
print(date.weekday); // 7
}
How to print the week name such as Monday in Dart.
How to get the name of the days of a week for a date in Dart?
There is no direct way to get with the In-built DateTime class and methods to get the name of the week.
use intl dependency
First, Add the
intl
dependency topubspec.yaml
dev_dependencies:
intl: any
Next, Import the intl package in the dart code file
import 'package:intl/intl.dart';
Create DateFormat object with format EEEE
Call DateFormat format method with a given date. Here is an example program
import 'package:intl/intl.dart';
void main() {
var date = DateTime.now();
print(DateFormat('EEEE').format(date)); // Sunday
}
use jiffy dependency
jiffy is a date and time utility library, First, Add the
jiffy
dependency topubspec.yaml
dependencies:
jiffy: ^5.0.0
Next, Import jiffy package in the dart code file
import 'package:jiffy/jiffy.dart';
Create a Jiffy object that returns the current date and time Call Jiffy.EEEE property that gives a week name. Here is an example program
import 'package:jiffy/jiffy.dart';
void main() {
var now = Jiffy();
print(now.EEEE);// Sunday
}
Conclusion
To summarize, Shows you multiple ways to get the week name for a given DateTime object in dart and flutter.