简体   繁体   English

将播放时间转换为格式化的字符串Javascript

[英]Converting Playback Time to a Formatted String Javascript

I have a timestamp pulled from a video that I want to convert into a user-friendly string in javascript. 我有一个要从视频中提取的时间戳,我想将其转换为JavaScript中用户友好的字符串。

let now = Player.getCurrentTime();

let minutes = Math.floor(now / 60.0);
let seconds = ((now / 60.0) - minutes) * 60;

console.log(minutes+":"+(seconds < 10 ? "0":"")+seconds);

The console.log statement using the conditional operator works really nicely for quick results. 使用条件运算符的console.log语句非常有效,可以快速获得结果。 Are there any basic Javascript functions that will allow me to create a string using the input as the console.log above? 是否有任何基本的Javascript函数可让我使用输入作为上述console.log来创建字符串?


UPDATE: 更新:

Quick shoutout to MrPickles for the prompt response. 快速向MrPickles喊叫 ,以便迅速做出响应。 I ended up just doing it manually via a helper function. 我最终只是通过帮助程序功能手动完成此操作。 If anyone needs a quick timestamp formatting, here's a quick freebie: 如果有人需要快速的时间戳格式,那么这里有一个免费的快速赠品:

function formatTime(timestamp) {

    let minutes = Math.floor(timestamp / 60.0);
    let seconds;
    let rawSeconds = ((now / 60.0) - minutes) * 60;

    if(rawSeconds < 10.0) {
        if(rawSeconds < 1.0) {
            seconds = rawSeconds.toPrecision(2);
        } else {
            seconds = rawSeconds.toPrecision(3);
        }
    } else {
        seconds = rawSeconds.toPrecision(4);
    }

    let mString = minutes.toString();
    let sString = seconds.toString();
    let displayTime = mString+":"+(seconds < 10 ? "0":"")+sString;
    return displayTime;
}

In short, no. 简而言之,没有。

There are date/time modules you can get to help with this but most of the popular ones are big. 有一些日期/时间模块可以帮助您解决这个问题,但是大多数流行的模块都很重要。 If this is all you are doing with the date then I would keep what you have. 如果这是您约会的全部工作,那么我会保留您所拥有的。

If you find you are doing a lot with dates and formatting then date-fns may be an options. 如果发现您对日期和格式做了很多工作,那么date-fns可能是一个选择。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM