1
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

【TypeScript】文字列形式で表現された時間を秒数に変換

Last updated at Posted at 2024-12-25

はじめに

TypeScript で文字列形式で表現された時間(例えば "00:05:30""30")を、秒数に変換する関数 convertToSeconds を実装しました。

実装

文字列(hh:mm:ss)を秒数に変換する convertToSeconds 関数を詳しく解説します。

interface TimeOptions {
    allowOverflow?: boolean; // オーバーフローの制限
    maxSeconds?: number; // 許容される最大秒数
}

function convertToSeconds(
    timeStr: string, 
    options: TimeOptions = { allowOverflow: true }
): number {
    const [second = 0, minute = 0, hour = 0]
        = timeStr.split(':').reverse().map(v => +v || 0);
    
    let totalSeconds;
    
    if (options.allowOverflow) {
        totalSeconds = hour * 3600 + minute * 60 + second;
    } else {
        const validMinute = Math.min(59, Math.max(0, minute));
        const validSecond = Math.min(59, Math.max(0, second));
        
        totalSeconds = hour * 3600 + validMinute * 60 + validSecond;
    }
    
    return options.maxSeconds !== undefined ? Math.min(totalSeconds, options.maxSeconds) : totalSeconds;
}

関数の概要
convertToSeconds 関数は、与えられた時間文字列をコロン(:)で区切り、その時間を秒単位に変換した数値で返します。入力には以下の形式がサポートされています。

  • 00:05:30(時:分:秒)
  • 05:30(分:秒)
  • 30(秒)

また、オプションで以下を指定できます。

  • allowOverflow
    • true: 70 分のような値をそのまま秒数に変換します。
    • false: 無効な値を丸めます。
      • 70 分(70:00)は無効とみなされ、最も近い有効な時間(59分)に丸められます。
  • maxSeconds
    • 指定された場合、計算された秒数がこの値を超えると、その値に丸められます。

使用例

convertToSeconds('10:20:30'); // 37230
convertToSeconds('20:30'); //. 1230
convertToSeconds('45');  // 45

convertToSeconds('70:80:90', { allowOverflow: true }); // 256890
// オーバーフローを制限
convertToSeconds('70:80:90', { allowOverflow: false }); // 255599

// 最大秒数制限
convertToSeconds('10:20:30', { maxSeconds: 3600 }); // 3600
convertToSeconds('00:00:59', { maxSeconds: 30 }); // 30 

// 空文字列や無効なフォーマットの入力
convertToSeconds(''); // 0
convertToSeconds('invalid'); // 0
convertToSeconds('1::2'); // 3602

おわりに

この関数は、さまざまな形式の時間文字列を秒数に変換する便利なツールです。入力が無効な場合は 0 を返すことで、エラーを防ぎます。

また、allowOverflowmaxSeconds のオプションにより、異なる要件や入力形式に対応可能です。

1
0
2

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?