1// Copyright 2018 The Chromium Authors. All rights reserved. 2// Use of this source code is governed by a BSD-style license that can be 3// found in the LICENSE file. 4 5import 'context.dart'; 6 7/// The current system clock instance. 8SystemClock get systemClock => context.get<SystemClock>(); 9 10/// A class for making time based operations testable. 11class SystemClock { 12 /// A const constructor to allow subclasses to be const. 13 const SystemClock(); 14 15 /// Create a clock with a fixed current time. 16 const factory SystemClock.fixed(DateTime time) = _FixedTimeClock; 17 18 /// Retrieve the current time. 19 DateTime now() => DateTime.now(); 20 21 /// Compute the time a given duration ago. 22 DateTime ago(Duration duration) { 23 return now().subtract(duration); 24 } 25} 26 27class _FixedTimeClock extends SystemClock { 28 const _FixedTimeClock(this._fixedTime); 29 30 final DateTime _fixedTime; 31 32 @override 33 DateTime now() => _fixedTime; 34} 35 36/// Format time as 'yyyy-MM-dd HH:mm:ss Z' where Z is the difference between the 37/// timezone of t and UTC formatted according to RFC 822. 38String formatDateTime(DateTime t) { 39 final String sign = t.timeZoneOffset.isNegative ? '-' : '+'; 40 final Duration tzOffset = t.timeZoneOffset.abs(); 41 final int hoursOffset = tzOffset.inHours; 42 final int minutesOffset = 43 tzOffset.inMinutes - (Duration.minutesPerHour * hoursOffset); 44 assert(hoursOffset < 24); 45 assert(minutesOffset < 60); 46 47 String twoDigits(int n) => (n >= 10) ? '$n' : '0$n'; 48 return '$t $sign${twoDigits(hoursOffset)}${twoDigits(minutesOffset)}'; 49} 50