LoginSignup
1
4

More than 5 years have passed since last update.

[JavaScript] 音声ファイルの経過時間(ミリ秒) を [分:秒] 形式に変換する

Last updated at Posted at 2016-07-14

やりたいこと

JavaScriptで、ミリ秒で渡される音声ファイルの経過時間を、[分:秒] 形式に変換したい。(最大で 59:59 まで表示できればよい。)

入力(ミリ秒) 出力
1000 0:01
122000 2:02

以下のコードはJSFiddleで実行できます。
https://jsfiddle.net/kjugk/4z1tLder/9/

JavaScript で書いてみる


function millisToMinutesAndSeconds(milliseconds){
  if(milliseconds >= 3600000){
    return "0:00" 
  }

  var seconds = parseInt((milliseconds / 1000) % 60, 10)
  var minutes = parseInt((milliseconds / (1000 * 60)) % 60, 10)

  seconds = (seconds < 10) ? "0" + seconds : seconds

  return minutes + ":" + seconds;
}

Moment.js を使う

Moment.js を使うと、以下のように書けました。

import moment from 'moment';

function millisToMinutesAndSeconds (milliseconds) {
  var duration = moment.duration(milliseconds);
  var seconds = duration.seconds();
  seconds = (seconds < 10) ? "0" + seconds : seconds;

  return duration.minutes() + ":" + seconds;
}
1
4
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
1
4