0
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?

(Node.js) hh-mm-ssモジュールを理解する

Posted at

はじめに

node.jsのコードの中で hh-mm-ssモジュールを使用する機会があったので、どのようなモジュールであるのか簡単にまとめたいと思います。

hh-mm-ssモジュールとは

時間の表現を管理するためのシンプルなライブラリです。
toMs, toS は、時間をそれぞれミリ秒、秒に変換する関数です。
fromMs, fromS は、ミリ秒や秒から「時間:分:秒」形式に変換します。

サンプルコード

hh-mm-ss.js
const TimeFormat = require("hh-mm-ss");

console.log(TimeFormat.toMs("00:01"));
console.log(TimeFormat.toS("02:00"));

console.log(TimeFormat.fromMs(3000));
console.log(TimeFormat.fromS(180));
console.log(TimeFormat.fromS(1800));
console.log(TimeFormat.fromS(18000));

const startTime = new Date();
console.log(`startTime: ${startTime}`);

setTimeout(() => {
  const endTime = new Date();
  console.log(`endTime: ${endTime}`);
  console.log(`Time difference in ms: ${endTime - startTime}`);
  console.log(
    `Time differencein in mm:ss: ${TimeFormat.fromMs(endTime - startTime)}`
  );
}, 2000);

・const TimeFormat = require("hh-mm-ss");
hh-mm-ss という外部パッケージを TimeFormat という名前でインポートしています。このパッケージは、時間を「時間:分:秒」形式に変換したり、その逆を行ったりする機能を提供します。

・console.log(TimeFormat.toMs("00:01"));
toMs("00:01") は、00:01 という時間(1秒)のフォーマットを、ミリ秒(1000ミリ秒 = 1秒) に変換します。結果は 1000 ミリ秒になります。

・console.log(TimeFormat.toS("02:00"));
toS("02:00") は、02:00(2分)のフォーマットを、秒 に変換します。結果は 120 秒です。

・console.log(TimeFormat.fromMs(3000));
fromMs はミリ秒から時間(mm:ss)形式に変換します。3000ミリ秒は 3秒なので、出力は "00:03" となります。

・console.log(TimeFormat.fromS(180));
fromS は秒を「時間:分:秒」のフォーマットに変換します。180 秒は 3分なので、出力は "03:00" となります。このようにhhの単位が必要でない時は、hhの部分は表示されません。

・console.log(TimeFormat.fromS(1800));
1800 秒は 30分、出力は "30:00"となります。

・console.log(TimeFormat.fromS(18000));
18000 秒は 5時間、出力は "5:00:00" となります。

・const startTime = new Date();
console.log(startTime: ${startTime});
startTime は現在の時刻を取得するために new Date() を使っています。
console.log によって、現在の時間が表示されます。

・setTimeout(() => {
const endTime = new Date();
console.log(endTime: ${endTime});
console.log(Time difference in ms: ${endTime - startTime});
console.log(Time difference in mm:ss: ${TimeFormat.fromMs(endTime - startTime)});
}, 2000);
setTimeout は2秒後に指定した関数を実行します。
2秒後、endTime という現在時刻を再度取得します。
endTime - startTime によって、2つの日時の差分をミリ秒で計算します。
TimeFormat.fromMs を使って、その差分を mm:ss 形式で表示します。

実行結果

スクリーンショット 2024-09-24 16.49.39.png

まとめ

node.jsのhh-mm-ssモジュールの使用方法についてまとめました。

Reference

0
0
0

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
0
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?