VOOZH about

URL: https://www.geeksforgeeks.org/dart/dart-dates-and-times/

⇱ Dart - Date and Time - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

Dart - Date and Time

Last Updated : 3 Apr, 2025

A DateTime object is a point in time. The time zone is either UTC or the local time zone. Accurate date-time handling is required in almost every data context. Dart has the marvelous built-in classes for date time and duration in dart:core.

Key Uses of DateTime in Dart:

  • Comparing and Calculating Dates: Execute operations such as addition, subtraction, and calculating the differences between dates.
  • Extracting Date-Time Components: Retrieve components such as the year, month, day, hour, minute, and second.
  • Handling Different Time Zones: Convert times between local time and Coordinated Universal Time (UTC).
  • Measuring Time Spans: Utilize the Duration class to manipulate intervals of time.

Creating and Manipulating DateTime

Example:


Output:

Current Date and Time: 2025-04-03 08:14:02.503
Y2K Date (Jan 1, 2000): 2000-01-01 00:00:00.000
Y2K Date (Jan 2, 2000): 2000-01-02 00:00:00.000
Y2K Date (UTC, Jan 1, 2000): 2000-01-01 00:00:00.000Z
Y2K Date from Unix Timestamp (UTC): 2000-01-01 00:00:00.000Z
Y2K Date from ISO 8601 String: 2000-01-01 00:00:00.000Z

The fromMillisecondsSinceEpoch property of a date returns the number of milliseconds since the Unix epoch—January 1, 1970, UTC.

Unix Epoch & Timestamp Validation

Example:


Output:

Y2K UTC Date Matches Expected Timestamp:
true
Unix Epoch Date Matches Expected Timestamp:
true

The Duration class can calculate the difference between two dates and move the date forward or backward.

Adding, Subtracting, and Finding Date Differences

Example:


Output:

Year after adding 366 days:
true
Month after subtracting 30 days:
true
Difference in days between Y2K and Y2001:
true

Conclusion

Dart's DateTime and Duration classes offer robust tools for handling dates, times, and time zones. Whether you need to compare dates, calculate durations, manipulate timestamps, or parse formatted date strings, these built-in classes make time-related operations in your applications much easier.

Comment
Article Tags:

Explore