🕤
Dartで時間を文字で保存して後で取り出して使えるのか?
これは何か?
SESのエンジニア:
「ある日上司にビジネスロジックを考えるように言われました💁♂️」
時間を文字列で保存しておいて、splitで取り出して、他の変数の時間の値に足せるのか?
上司の発言:
「doubleだと12:00:13とかめんどっちーですよね(笑)
文字列でいれといて、コードでsplitなりなんなりで必要な値は取れますし。」
SESのエンジニア:
「そんなことできるの?」
とりあえずやってみよう。
splitメソッドとは?
内部実装を見ると、指定したパターンに一致する部分で文字列を分割し、その結果を文字列のリストとして返すものだとわかりました。
内部のコード:
List<String> split(Pattern pattern);
/// Splits the string, converts its parts, and combines them into a new
/// string.
///
/// The [pattern] is used to split the string
/// into parts and separating matches.
/// Each match of [Pattern.allMatches] of [pattern] on this string is
/// used as a match, and the substrings between the end of one match
/// (or the start of the string) and the start of the next match (or the
/// end of the string) is treated as a non-matched part.
/// (There is no omission of leading or trailing empty matchs, like
/// in [split], all matches and parts between the are included.)
///
/// Each match is converted to a string by calling [onMatch]. If [onMatch]
/// is omitted, the matched substring is used.
///
/// Each non-matched part is converted to a string by a call to [onNonMatch].
/// If [onNonMatch] is omitted, the non-matching substring itself is used.
///
/// Then all the converted parts are concatenated into the resulting string.
/// ```dart
/// final result = 'Eats shoots leaves'.splitMapJoin(RegExp(r'shoots'),
/// onMatch: (m) => '${m[0]}', // (or no onMatch at all)
/// onNonMatch: (n) => '*');
/// print(result); // *shoots*
/// ```
String splitMapJoin(Pattern pattern,
{String Function(Match)? onMatch, String Function(String)? onNonMatch});
これが上司に提出したビジネスロジック
ポイントは、:
を指定して:
で区切ってある文字列を取り出して、Listだから、[0],[1],[2]
と指定してあげればListの中から、欲しい文字列の数字を取れます。これをint.parse
で文字から数値に変換してあげれば、時間として扱うことができるビジネスロジックを作れます。
void main() {
String timeString = "12:00:13";
List<String> timeParts = timeString.split(':');
int hours = int.parse(timeParts[0]);
int minutes = int.parse(timeParts[1]);
int seconds = int.parse(timeParts[2]);
print('Hours: $hours, Minutes: $minutes, Seconds: $seconds');
// 他の時間変数に足す
int extraHours = 1;
int extraMinutes = 30;
int extraSeconds = 15;
hours += extraHours;
minutes += extraMinutes;
seconds += extraSeconds;
print('Updated time - Hours: $hours, Minutes: $minutes, Seconds: $seconds');
}
実行結果:
Hours: 12, Minutes: 0, Seconds: 13
Updated time - Hours: 13, Minutes: 30, Seconds: 28
Exited.
最後に
double型で時間を保存して扱うと手間らしくて、文字で保存して後で取り出して使えば良いということでプログラムを考えてみました。
Discussion