web-dev-qa-db-ja.com

JavaScriptで時間ミリ秒を時間、分、秒の形式に変換するにはどうすればよいですか?

時間はミリ秒単位ですが、変換後の時間は00:00:00のようにしたいです。

例:ミリ秒= 86400000。 00:00:00のように、そのミリ秒で何時間か欲しい

JavaScriptで取得する方法は?

45
cheliyan

以下に示すようにjavascriptで関数を作成してこれを行う方法はどうですか。

function msToTime(duration) {
  var milliseconds = parseInt((duration % 1000) / 100),
    seconds = Math.floor((duration / 1000) % 60),
    minutes = Math.floor((duration / (1000 * 60)) % 60),
    hours = Math.floor((duration / (1000 * 60 * 60)) % 24);

  hours = (hours < 10) ? "0" + hours : hours;
  minutes = (minutes < 10) ? "0" + minutes : minutes;
  seconds = (seconds < 10) ? "0" + seconds : seconds;

  return hours + ":" + minutes + ":" + seconds + "." + milliseconds;
}
console.log(msToTime(300000))
77
Dusht

ミリ秒単位の時間を人間が読める形式に変換します。

 function timeConversion(millisec) {

        var seconds = (millisec / 1000).toFixed(1);

        var minutes = (millisec / (1000 * 60)).toFixed(1);

        var hours = (millisec / (1000 * 60 * 60)).toFixed(1);

        var days = (millisec / (1000 * 60 * 60 * 24)).toFixed(1);

        if (seconds < 60) {
            return seconds + " Sec";
        } else if (minutes < 60) {
            return minutes + " Min";
        } else if (hours < 24) {
            return hours + " Hrs";
        } else {
            return days + " Days"
        }
    }

"Out Put Sample"

38
Nofi

私は同じ問題を抱えていました、これは私がやったことです:

function parseMillisecondsIntoReadableTime(milliseconds){
  //Get hours from milliseconds
  var hours = milliseconds / (1000*60*60);
  var absoluteHours = Math.floor(hours);
  var h = absoluteHours > 9 ? absoluteHours : '0' + absoluteHours;

  //Get remainder from hours and convert to minutes
  var minutes = (hours - absoluteHours) * 60;
  var absoluteMinutes = Math.floor(minutes);
  var m = absoluteMinutes > 9 ? absoluteMinutes : '0' +  absoluteMinutes;

  //Get remainder from minutes and convert to seconds
  var seconds = (minutes - absoluteMinutes) * 60;
  var absoluteSeconds = Math.floor(seconds);
  var s = absoluteSeconds > 9 ? absoluteSeconds : '0' + absoluteSeconds;


  return h + ':' + m + ':' + s;
}


var time = parseMillisecondsIntoReadableTime(86400000);

alert(time);
16
xno

これはYouTube動画のような時間を返します

    function getYoutubeLikeToDisplay(millisec) {
        var seconds = (millisec / 1000).toFixed(0);
        var minutes = Math.floor(seconds / 60);
        var hours = "";
        if (minutes > 59) {
            hours = Math.floor(minutes / 60);
            hours = (hours >= 10) ? hours : "0" + hours;
            minutes = minutes - (hours * 60);
            minutes = (minutes >= 10) ? minutes : "0" + minutes;
        }

        seconds = Math.floor(seconds % 60);
        seconds = (seconds >= 10) ? seconds : "0" + seconds;
        if (hours != "") {
            return hours + ":" + minutes + ":" + seconds;
        }
        return minutes + ":" + seconds;
    }

出力:

  • getYoutubeLikeToDisplay(129900)= "2:10"
  • getYoutubeLikeToDisplay(1229900)= "20:30"
  • getYoutubeLikeToDisplay(21229900)= "05:53:50"
13
Chand

@Chand回答に基づきます。これはTypeScriptの実装です。 JSの型を強制するよりも少し安全です。型注釈を削除する場合、有効なJSである必要があります。また、新しい文字列関数を使用して時間を正規化します。

function displayTime(millisec: number) {
 const normalizeTime = (time: string): string => (time.length === 1) ? time.padStart(2, '0') : time;

 let seconds: string = (millisec / 1000).toFixed(0);
 let minutes: string = Math.floor(parseInt(seconds) / 60).toString();
 let hours: string = '';

 if (parseInt(minutes) > 59) {
   hours = normalizeTime(Math.floor(parseInt(minutes) / 60).toString());
   minutes = normalizeTime((parseInt(minutes) - (parseInt(hours) * 60)).toString());
 }
 seconds = normalizeTime(Math.floor(parseInt(seconds) % 60).toString());

 if (hours !== '') {
    return `${hours}:${minutes}:${seconds}`;
 }
   return `${minutes}:${seconds}`;
}
2
KevinOrfas

このソリューションでは、1つのfunctionを使用してミリ秒をparts objectに分割し、別のfunctionを使用してparts objectをフォーマットします。

2つの形式関数を作成しました。1つは要求どおりで、もう1つはわかりやすい文字列を印刷し、単数/複数を考慮して、ミリ秒を表示するオプションが含まれています。

function parseDuration(duration) {
  let remain = duration

  let days = Math.floor(remain / (1000 * 60 * 60 * 24))
  remain = remain % (1000 * 60 * 60 * 24)

  let hours = Math.floor(remain / (1000 * 60 * 60))
  remain = remain % (1000 * 60 * 60)

  let minutes = Math.floor(remain / (1000 * 60))
  remain = remain % (1000 * 60)

  let seconds = Math.floor(remain / (1000))
  remain = remain % (1000)

  let milliseconds = remain

  return {
    days,
    hours,
    minutes,
    seconds,
    milliseconds
  };
}

function formatTime(o, useMilli = false) {
  let parts = []
  if (o.days) {
    let ret = o.days + ' day'
    if (o.days !== 1) {
      ret += 's'
    }
    parts.Push(ret)
  }
  if (o.hours) {
    let ret = o.hours + ' hour'
    if (o.hours !== 1) {
      ret += 's'
    }
    parts.Push(ret)
  }
  if (o.minutes) {
    let ret = o.minutes + ' minute'
    if (o.minutes !== 1) {
      ret += 's'
    }
    parts.Push(ret)

  }
  if (o.seconds) {
    let ret = o.seconds + ' second'
    if (o.seconds !== 1) {
      ret += 's'
    }
    parts.Push(ret)
  }
  if (useMilli && o.milliseconds) {
    let ret = o.milliseconds + ' millisecond'
    if (o.milliseconds !== 1) {
      ret += 's'
    }
    parts.Push(ret)
  }
  if (parts.length === 0) {
    return 'instantly'
  } else {
    return parts.join(' ')
  }
}

function formatTimeHMS(o) {
  let hours = o.hours.toString()
  if (hours.length === 1) hours = '0' + hours

  let minutes = o.minutes.toString()
  if (minutes.length === 1) minutes = '0' + minutes

  let seconds = o.seconds.toString()
  if (seconds.length === 1) seconds = '0' + seconds

  return hours + ":" + minutes + ":" + seconds
}

function formatDurationHMS(duration) {
  let time = parseDuration(duration)
  return formatTimeHMS(time)
}

function formatDuration(duration, useMilli = false) {
  let time = parseDuration(duration)
  return formatTime(time, useMilli)
}


console.log(formatDurationHMS(57742343234))

console.log(formatDuration(57742343234))
console.log(formatDuration(5423401000))
console.log(formatDuration(500))
console.log(formatDuration(500, true))
console.log(formatDuration(1000 * 30))
console.log(formatDuration(1000 * 60 * 30))
console.log(formatDuration(1000 * 60 * 60 * 12))
console.log(formatDuration(1000 * 60 * 60 * 1))
1
Steven Spungin

ここに私の解決策があります

let h,m,s;
h = Math.floor(timeInMiliseconds/1000/60/60);
m = Math.floor((timeInMiliseconds/1000/60/60 - h)*60);
s = Math.floor(((timeInMiliseconds/1000/60/60 - h)*60 - m)*60);

//時間形式00:00:00を取得します

s < 10 ? s = `0${s}`: s = `${s}`
m < 10 ? m = `0${m}`: m = `${m}`
h < 10 ? h = `0${h}`: h = `${h}`


console.log(`${s}:${m}:${h}`);
1
Tin Pritišanac

私のために働いた

msToTime(milliseconds) {
    //Get hours from milliseconds
    var hours = milliseconds / (1000*60*60);
    var absoluteHours = Math.floor(hours);
    var h = absoluteHours > 9 ? absoluteHours : '0' + absoluteHours;

    //Get remainder from hours and convert to minutes
    var minutes = (hours - absoluteHours) * 60;
    var absoluteMinutes = Math.floor(minutes);
    var m = absoluteMinutes > 9 ? absoluteMinutes : '0' +  absoluteMinutes;

    //Get remainder from minutes and convert to seconds
    var seconds = (minutes - absoluteMinutes) * 60;
    var absoluteSeconds = Math.floor(seconds);
    var s = absoluteSeconds > 9 ? absoluteSeconds : '0' + absoluteSeconds;

    return h == "00" ? m + ':' + s : h + ':' + m + ':' + s;
}
1
Hassan

私の解決策

var sunriseMills = 1517573074000;         // sunrise in NewYork on Feb 3, 2018  - UTC time
var offsetCityMills = -5 * 3600 * 1000;   // NewYork delay to UTC 
var offsetDeviceMills =  new Date().getTimezoneOffset() * 60 * 1000 ;  // eg. I live in Romania (UTC+2) >> getTimezoneOffset() = 120

var textTime = new Date(sunriseMills + offsetCityMills + offsetDeviceMills) 
    .toLocaleTimeString('en-US', { hour: 'numeric', minute: 'numeric' });

textTimeは '7.04 AM'になります

1
Dan Alboteanu

上記のスニペットは、1日以上のケースでは機能しません(これらは単に無視されます)。

このために使用できます:

function convertMS(ms) {
    var d, h, m, s;
    s = Math.floor(ms / 1000);
    m = Math.floor(s / 60);
    s = s % 60;
    h = Math.floor(m / 60);
    m = m % 60;
    d = Math.floor(h / 24);
    h = h % 24;
    h += d * 24;
    return h + ':' + m + ':' + s;
}

enter image description here

https://Gist.github.com/remino/1563878 に感謝

1
think win win

私は1日、24時間までしか時間を必要としませんでした、これは私の意見でした:

const milliseconds = 5680000;

const hours = `0${new Date(milliseconds).getHours() - 1}`.slice(-2);
const minutes = `0${new Date(milliseconds).getMinutes()}`.slice(-2);
const seconds = `0${new Date(milliseconds).getSeconds()}`.slice(-2);

const time = `${hours}:${minutes}:${seconds}`
console.log(time);

必要に応じて、この方法で同様の日数を得ることができます。

0

TypeScriptを使用している場合、これはあなたにとって良いことです

enum ETime {
  Seconds = 1000,
  Minutes = 60000,
  Hours = 3600000,
  SecInMin = 60,
  MinInHours = 60,
  HoursMod = 24,
  timeMin = 10,
}

interface ITime {
  millis: number
  modulo: number
}

const Times = {
  seconds: {
    millis: ETime.Seconds,
    modulo: ETime.SecInMin,
  },
  minutes: {
    millis: ETime.Minutes,
    modulo: ETime.MinInHours,
  },
  hours: {
    millis: ETime.Hours,
    modulo: ETime.HoursMod,
  },
}

const dots: string = ":"

const msToTime = (duration: number, needHours: boolean = true): string => {
  const getCorrectTime = (divider: ITime): string => {
    const timeStr: number = Math.floor(
      (duration / divider.millis) % divider.modulo,
    )

    return timeStr < ETime.timeMin ? "0" + timeStr : String(timeStr)
  }

  return (
    (needHours ? getCorrectTime(Times.hours) + dots : "") +
    getCorrectTime(Times.minutes) +
    dots +
    getCorrectTime(Times.seconds)
  )
}
0
Jonathan Biteau

私の実装では、Moment.jsを使用しました。

export default (value) => 
  const duration = moment.duration(value);

  const milliseconds = duration.milliseconds();
  const seconds = duration.seconds();
  const minutes = duration.minutes();
  const hours = duration.hours();
  const day = duration.days();

  const sDay = `${day}d `;
  const sHours = (hours < 10) ? `0${hours}h ` : `${hours}h `;
  const sMinutes = (minutes < 10) ? `0${minutes}' ` : `${minutes}' `;
  const sSeconds = (seconds < 10) ? `0${seconds}" ` : `${seconds}" `;
  const sMilliseconds = `${milliseconds}ms`;

  ...
}

文字列を取得したら、好きなように構成しました。

0
Luca Tagliabue