javascript 有没有一种简单的方法可以使用 moment.js 将十进制时间(例如 1.074 分钟)转换为 mm:ss 格式?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/17599054/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Is there a simple way to convert a decimal time (e.g. 1.074 minutes) into mm:ss format using moment.js?
提问by JAC
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 am currently using a function which doesn't work too well with negative times (it outputs the value in '-m:ss' format):
我想知道是否有一种简单的方法,使用 moment.js 库,将十进制时间间隔(例如,1.074 分钟)转换为其等效的“mm:ss”值。我目前正在使用一个在负时间下效果不佳的函数(它以“-m:ss”格式输出值):
function secTommss(sec){
var min = Math.floor(sec/60)
sec = Math.round(Math.abs(sec) % 60);
return min + ":" + (sec < 10 ? "0" + sec : sec)
}
回答by Matt Johnson-Pint
Here is some JavaScript that will do what you are asking:
这是一些可以满足您要求的 JavaScript:
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 coulduse moment.js durations, such as
您可以使用 moment.js durations,例如
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.
但是目前,没有像您要求的那样以 mm:ss 格式格式化持续时间的干净方法,因此无论如何您都会重新完成大部分工作。
回答by kayakyakr
Using moment:
使用时刻:
function formatMinutes(mins){
return moment().startOf('day').add(mins, 'minutes').format('m:ss');
}
回答by dandavis
using just js, here's a really simple and fast way to do this for up to 12 hours:
仅使用 js,这是一种非常简单且快速的方法,最多可使用 12 小时:
function secTommss2(sec){
return new Date(sec*1000).toUTCString().split(" ")[4]
}
回答by Bullsized
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