-
-
Notifications
You must be signed in to change notification settings - Fork 4
/
duration_extensions.dart
84 lines (80 loc) · 3.05 KB
/
duration_extensions.dart
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
part of '/katana.dart';
/// Provides extended methods for [Duration].
///
/// [Duration]用の拡張メソッドを提供します。
extension DurationExtensions on Duration {
/// Parses [Duration] to [String] according to the definition given in [format].
///
/// The following parameters are available
///
/// [format]で与えられた定義に従って[Duration]を[String]にパースします。
///
/// 下記のパラメーターを利用することが可能です。
///
/// - `d` Displays days. 日付を表示します。
/// - `H` Displays hours. 時間を表示します。
/// - `m` Display minutes. 分を表示します。
/// - `s` Display seconds. 秒を表示します。
/// - `HH` Displays hours in two digits. 時間を2桁で表示します。
/// - `mm` Displays minutes in two digits. 分を2桁で表示します。
/// - `ss` Displays seconds in two digits. 秒を2桁で表示します。
/// - `S` Display milli-seconds. ミリ秒を表示します。
/// - `M` Display micro-seconds. マイクロ秒を表示します。
///
/// For example,
///
/// ```dart
/// final duration = const Duration(days: 6, hours: 12);
/// print(duration.format("d : H")); // 6 : 12
/// ```
String format(String format) {
assert(format.isNotEmpty, "The format is empty.");
String twoDigits(int n) => n.toString().padLeft(2, "0");
String threeDigits(int n) => n.toString().padLeft(3, "0");
final hours = inHours.remainder(24);
final minutes = inMinutes.remainder(60);
final seconds = inSeconds.remainder(60);
final milliSeconds = inMilliseconds.remainder(1000);
final microSeconds = inMicroseconds.remainder(1000);
return format
.replaceAll("d", inDays.toString())
.replaceAll("HH", twoDigits(hours))
.replaceAll("mm", twoDigits(minutes))
.replaceAll("ss", twoDigits(seconds))
.replaceAll("H", hours.toString())
.replaceAll("m", minutes.toString())
.replaceAll("s", seconds.toString())
.replaceAll("S", threeDigits(milliSeconds))
.replaceAll("M", threeDigits(microSeconds));
}
/// Parse from [Duration] to [String] corresponding to [format].
///
/// The output will be in the format `08:30:12`.
///
/// [Duration]から[format]に対応した[String]にパースします。
///
/// `08:30:12`のような形式で出力されます。
String hhMMSS() {
return format("HH:mm:ss");
}
/// Parse from [Duration] to [String] corresponding to [format].
///
/// The output will be in the format `30:12`.
///
/// [Duration]から[format]に対応した[String]にパースします。
///
/// `30:12`のような形式で出力されます。
String mmSS() {
return format("mm:ss");
}
/// Parse from [Duration] to [String] corresponding to [format].
///
/// The output will be in the format `08:30`.
///
/// [Duration]から[format]に対応した[String]にパースします。
///
/// `08:30`のような形式で出力されます。
String hhMM() {
return format("HH:mm");
}
}