3
2

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

Pure JSでAM、PM表記への変換書いてみた

Posted at

hh:mm 表記の時刻を AMPM 表記に変換する。
まず、全体のコードはこちら、

// 実装した関数
const convertMeridian = time => {
  const [h, m] = time.split(":");
  const meridian = ["AM", "PM"][Math.floor(h / 12)];
  return meridian + [h % 12, m].map(v => ("0" + v).slice(-2)).join(":");
}

//実行例
const time = "12:19";
console.log(convertMeridian(time));
// 出力 PM00:19

解説

const [h, m] = time.split(":");
// h = 12, m = 19

const meridian = ["AM", "PM"][Math.floor(h / 12)];
// ["AM", "PM"] と言う配列を生成
// h は0-23なので、12で割って0.xx、1.xxという小数にし、
// Math.floorで切り捨てることで 配列のIndex を指定する

return meridian + [h % 12, m].map(v => ("0" + v).slice(-2)).join(":")
// 時間を 12 で割った余りと、分を2桁の文字列にフォーマット
// ":" で間をつないで AM、PMを追加
3
2
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
3
2

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?