Is there a simple way to convert a decimal time (e.g. 1.074 minutes) into mm:ss format using moment.js?

前端 未结 4 1629
無奈伤痛
無奈伤痛 2020-12-16 03:26

I was wondering if there\'s a simple way, using moment.js library, to transform a decimal time interval (for example, 1.074 minutes) into its equivalent \'mm:ss\' value. I a

相关标签:
4条回答
  • 2020-12-16 04:02

    using just js, here's a really simple and fast way to do this for up to 12 hours:

    function secTommss2(sec){
      return new Date(sec*1000).toUTCString().split(" ")[4]
    }
    
    0 讨论(0)
  • 2020-12-16 04:10

    Using moment:

    function formatMinutes(mins){
      return moment().startOf('day').add(mins, 'minutes').format('m:ss');
    }
    
    0 讨论(0)
  • 2020-12-16 04:20

    Here is some JavaScript that will do what you are asking:

    function minTommss(minutes){
     var sign = minutes < 0 ? "-" : "";
     var min = Math.floor(Math.abs(minutes));
     var sec = Math.floor((Math.abs(minutes) * 60) % 60);
     return sign + (min < 10 ? "0" : "") + min + ":" + (sec < 10 ? "0" : "") + sec;
    }
    

    Examples:

    minTommss(3.5)        // "03:30"
    minTommss(-3.5)       // "-03:30"
    minTommss(36.125)     // "36:07"
    minTommss(-9999.999)  // "-9999:59"
    

    You could use moment.js durations, such as

    moment.duration(1.234, 'minutes')
    

    But currently, there's no clean way to format a duration in mm:ss like you asked, so you'd be re-doing most of that work anyway.

    0 讨论(0)
  • 2020-12-16 04:29

    maybe I am a bit late to the party, but still... my two cents:

    you can build the variable in seconds, parse it as a date, and then cut it to a string or whatever format you want to use it:

    let totalTimeInSeconds = 1.074 * 60;
    let result = new Date(null, null, null, null, null, totalTimeInSeconds);
    console.log(result.toTimeString().split(' ').[0].substring(3));
    

    and the output will be:

    01:14
    
    0 讨论(0)
提交回复
热议问题