Dart: Datetime
The class Datetime is a combination of date and time along with the time zone. It is used to perform various date-time operations like formatting, parsing, timezones, etc.
Example:
void main() {
var now = DateTime.now();
print(now); // 2021-08-22 16:00:00.000
}
Creating a specific date:
void main() {
var date = DateTime(2021, 08, 22);
print(date); // 2021-08-22 00:00:00.000
}
Split the date and time:
void main() {
var now = DateTime.now();
print(now.year); // 2021
print(now.month); // 8
print(now.day); // 22
print(now.hour); // 16
print(now.minute); // 0
print(now.second); // 0
print(now.millisecond); // 0
print(now.microsecond); // 0
}
We can manipulate for data and adding or subtracting days, months, years, etc.
Example: Adding 2 days and 13 hours to the current date:
void main() {
var now = DateTime.now();
var newDate = now.add(Duration(days: 2, hours: 13));
print(newDate);
}
Another example: Subtracting 2 days and 13 hours to the current date:
void main() {
var now = DateTime.now();
var newDate = now.subtract(Duration(days: 2, hours: 13));
print(newDate);
}
Another example more complex:
📅 If my bride and I are going to get married in 2 years, 3 months and 5 days, what date will it be?
var now = DateTime.now();
var weddingDate = DateTime(now.year + 2, now.month + 3, now.day + 5);
print(weddingDate);
We can also compare dates:
void main() {
var now = DateTime.now();
var newDate = now.add(Duration(days: 2, hours: 13));
print(now.isBefore(newDate)); // true
print(now.isAfter(newDate)); // false
}
Intl
Intl is a package provided by Dart to perform internationalization (i18n) and localization (l10n) tasks, such as formatting dates, numbers, and strings into language-specific messages, and performing bidirectional text transformations.
Example:
import 'package:intl/intl.dart';
void main() {
var now = DateTime.now();
DateFormat.MMMMd().format(now); // July 10
DateFormat.yMMMMd().format(now); // July 10, 2019
DateFormat.yMd().format(now); // 7/10/2019
DateFormat('EEEE, d MMMM, yyyy').format(now); // Wednesday, 10 July, 2019
DateFormat('kk:mm:ss').format(now); // 14:18:02
DateFormat('hh:mm a').format(now); // 02:18 PM
DateFormat('yyyy-MM-dd – kk:mm').format(now); // 2019-07-10 – 14:18
}