← All languages
Dart function of the day
Random

DateTime.now

Create a DateTime representing the current date and time.

Description

The DateTime.now constructor creates a DateTime object set to the current date and time in the local time zone. It uses the system clock to determine the current moment and is the most common way to get the current time in Dart.

The returned DateTime object provides properties like year, month, day, hour, minute, second, and millisecond. It can be formatted, compared, and used in arithmetic with Duration objects for time calculations.

For UTC timestamps, use DateTime.now().toUtc() or DateTime.timestamp() which directly returns a UTC DateTime. When testing code that depends on the current time, consider injecting a clock abstraction rather than calling DateTime.now directly.

Example

var now = DateTime.now();
print(now); // e.g. 2024-01-15 14:30:00.000
print(now.year); // 2024
print(now.weekday); // 1-7 (Monday-Sunday)

Reference