{

How to Get Current Date in Dart or Flutter Programming| Dart by Example


Current Date and time in Dart

This example shows how to get the Current Date and time in the Dart or Flutter programming language.

  • Current Date and time using the DateTime.now() function.
  • Current Time without Date using the DateFormat.Hms().format() method
  • Current Date only without hours minutes, Using DateFormat.yMd().format(dateTime); function.

How to get the Current Date and time in Dart

Dart provides the DateTime class to process Date and Time-related functions.

The now() method returns the current date and time.

Here is an example to get the Current Date and time

main() {
    DateTime dateTime = DateTime.now();

  print(dateTime.toString()); //2022-03-04 12:35:38.997
  int currentYear = dateTime.year;
  print(currentYear.toString()); //2022
}

Output:

//2022-03-04 12:35:38.997
//2022

How to get Current time in hours and time(hh and mm) in Dart

This example returns only time in hours, minutes, and seconds and the format is hh:mm:ss

  • Import the intl/intl.dart package into the program
  • create a DateTime object with the now() function.
  • Call DateFormat method Hms() where Hms is a format defined by a dart.
  • pass DateTime object to format() method.
  • It returns the current time

Here is an example

import 'package:intl/intl.dart';

main() {
  DateTime dateTime = DateTime.now();
  String timeFormat = DateFormat.Hms().format(dateTime);
  print(timeFormat); //12:42:49
}

How to get Current Date only in Dart

This example gets the current date in the MM/DD/YYYY format only.

  • Import the intl/intl.dart package into the program using the import keyword
  • create a DateTime object with the now() function.
  • Call DateFormat method yMd() function where yMd is an format(MM/DD/YYYY) defined by dart.
  • pass DateTime object to format() method.
  • It returns the current time

Here is an example

import 'package:intl/intl.dart';

main() {
  DateTime dateTime = DateTime.now();
  String timeFormat = DateFormat.yMd().format(dateTime);
  print(timeFormat); //3/4/2022
}

Conclusion

Learned how to convert String date into DateTime in multiple ways.

THE BEST NEWSLETTER ANYWHERE
Join 6,000 subscribers and get a daily digest of full stack tutorials delivered to your inbox directly.No spam ever. Unsubscribe any time.

Similar Posts
Subscribe
You'll get a notification every time a post gets published here.





Related posts

Perl How to: Find a Given Variable String is numeric or not

Dart/Flutter: Check if String is Empty, Null, or Blank example

How to generate Unique Id UUID in Dart or Flutter Programming| Dart or Flutterby Example

How to Sort List of numbers or String in ascending and descending in Dart or Flutter example

Dart Enum comparison operator| Enum compareByIndex example| Flutter By Example

Dart Example - Program to check Leap year or not

Dart Example to count the number of digits in a number| Decimals Count in Dart