Dart:
Getting the current date

How to:

Dart’s core library provides straightforward access to the current date and time through the DateTime class. Here’s the basic example to get the current date:

void main() {
  DateTime now = DateTime.now();
  print(now); // Example output: 2023-04-12 10:00:00.000
}

If you only need the date part (year, month, day), you can format the DateTime object:

void main() {
  DateTime now = DateTime.now();
  String formattedDate = "${now.year}-${now.month}-${now.day}";
  print(formattedDate); // Example output: 2023-04-12
}

Dart doesn’t include a built-in library for more complex date formatting, but you can use the intl package for this purpose. First, add the package to your pubspec.yaml:

dependencies:
  intl: ^0.17.0

Then, you can format dates easily:

import 'package:intl/intl.dart';

void main() {
  DateTime now = DateTime.now();
  String formattedDate = DateFormat('yyyy-MM-dd').format(now);
  print(formattedDate); // Example output: 2023-04-12
}

For more advanced formatting options, explore the DateFormat class provided by the intl package, which supports a wide range of patterns and locales.