Date.fromTime constructor

Date.fromTime(
  1. DateTime time, {
  2. Duration? tzOffset,
})

Extracts the Date from the given time.

By default this acts the same as just grabbing the year/month/day fields out of the given DateTime. But if a tzOffset is provided, this'll convert the time to the given timezone first:

// Midnight UTC. In Zurich, it's November 17th, but in Atlanta, it's
// still November 16th.
var time = new DateTime.utc(2015, 11, 17);
var est = new Duration(hours: -5); // Eastern time; GMT -5

new Date.fromTime(time); // 2015-11-17
new Date.fromTime(time, tzOffset: est); // 2015-11-16

Implementation

factory Date.fromTime(DateTime time, {Duration? tzOffset}) {
  if (time.timeZoneOffset.inMicroseconds.isNaN) {
    throw ArgumentError.value(time, 'time', 'has a NaN time zone offset');
  }

  tzOffset ??= time.timeZoneOffset;
  if (tzOffset.inMicroseconds.isNaN) {
    throw ArgumentError.value(tzOffset, 'tzOffset', 'has a NaN duration');
  }

  final localTime = time.add(tzOffset - time.timeZoneOffset);
  return Date(localTime.year, localTime.month, localTime.day);
}