1 | // Copyright 2014 The Flutter 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 | |
5 | /// A class for making time based operations testable. |
6 | class SystemClock { |
7 | /// A const constructor to allow subclasses to be const. |
8 | const SystemClock(); |
9 | |
10 | /// Create a clock with a fixed current time. |
11 | const factory SystemClock.fixed(DateTime time) = _FixedTimeClock; |
12 | |
13 | /// Retrieve the current time. |
14 | DateTime now() => DateTime.now(); |
15 | |
16 | /// Compute the time a given duration ago. |
17 | DateTime ago(Duration duration) { |
18 | return now().subtract(duration); |
19 | } |
20 | } |
21 | |
22 | class _FixedTimeClock extends SystemClock { |
23 | const _FixedTimeClock(this._fixedTime); |
24 | |
25 | final DateTime _fixedTime; |
26 | |
27 | @override |
28 | DateTime now() => _fixedTime; |
29 | } |
30 | |
31 | /// Format time as 'yyyy-MM-dd HH:mm:ss Z' where Z is the difference between the |
32 | /// timezone of t and UTC formatted according to RFC 822. |
33 | String formatDateTime(DateTime t) { |
34 | final String sign = t.timeZoneOffset.isNegative ? '-': '+'; |
35 | final Duration tzOffset = t.timeZoneOffset.abs(); |
36 | final int hoursOffset = tzOffset.inHours; |
37 | final int minutesOffset = tzOffset.inMinutes - (Duration.minutesPerHour * hoursOffset); |
38 | assert(hoursOffset < 24); |
39 | assert(minutesOffset < 60); |
40 | |
41 | String twoDigits(int n) => (n >= 10) ? '$n ': '0$n '; |
42 | return '$t $sign ${twoDigits(hoursOffset)}${twoDigits(minutesOffset)}'; |
43 | } |
44 |