LocalTime constructor

LocalTime(
  1. int hour,
  2. int minute,
  3. int second, {
  4. int? ms,
  5. int? us,
  6. int? ns,
})

Creates a local time at the given hour, minute, second and millisecond or microseconds or nanoseconds within the second.

  • hour: The hour of day.
  • minute: The minute of the hour.
  • second: The second of the minute.
  • ms: The millisecond of the second.
  • us: The microsecond within the second.
  • ns: The nanosecond within the second.

Returns: The resulting time.

When\if https://github.com/dart-lang/sdk/issues/7056 becomes implemented, second will become optional, like this: (int hour, int minute, [int second], {int ms, int us, int ns}). The is a planned backwards compatible public API change.

Implementation

factory LocalTime(int hour, int minute, int second, {int? ms, int? us, int? ns}) {
  // Avoid the method calls which give a decent exception unless we're actually going to fail.
  if (hour < 0 || hour >= TimeConstants.hoursPerDay ||
      minute < 0 || minute >= TimeConstants.minutesPerHour ||
      second < 0 || second >= TimeConstants.secondsPerMinute) {
    Preconditions.checkArgumentRange('hour', hour, 0, TimeConstants.hoursPerDay - 1);
    Preconditions.checkArgumentRange('minute', minute, 0, TimeConstants.minutesPerHour - 1);
    Preconditions.checkArgumentRange('second', second, 0, TimeConstants.secondsPerMinute - 1);
  }

  var nanoseconds
      = hour * TimeConstants.nanosecondsPerHour
      + minute * TimeConstants.nanosecondsPerMinute
      + second * TimeConstants.nanosecondsPerSecond;
  ;

  // Only one sub-second variable may be implemented.
  // todo: is there a more performant check here?
  if (ms != null) {
    if (us != null) throw ArgumentError(_munArgumentError);
    if (ns != null) throw ArgumentError(_munArgumentError);
    if (ms < 0 || ms >= TimeConstants.millisecondsPerSecond) Preconditions.checkArgumentRange('milliseconds', ms, 0, TimeConstants.millisecondsPerSecond - 1);
    nanoseconds += ms * TimeConstants.nanosecondsPerMillisecond;
  }
  else if (us != null) {
    if (ns != null) throw ArgumentError(_munArgumentError);
    if (us < 0 || us >= TimeConstants.microsecondsPerSecond) Preconditions.checkArgumentRange('microseconds', us, 0, TimeConstants.microsecondsPerSecond - 1);
    nanoseconds += us * TimeConstants.nanosecondsPerMicrosecond;
  }
  else if (ns != null) {
    if (ns < 0 || ns >= TimeConstants.nanosecondsPerSecond) Preconditions.checkArgumentRange('nanoseconds', ns, 0, TimeConstants.nanosecondsPerSecond - 1);
    nanoseconds += ns;
  }

  return LocalTime._(nanoseconds);
}