EdwardZZZ / articles

工作点滴记录
2 stars 0 forks source link

格式化数字 #13

Open EdwardZZZ opened 7 years ago

EdwardZZZ commented 7 years ago
将1位数字格式化成两位
(n+'').length === 1 ? '0' + n : n;
(n+'').replace(/^(\d{1})$/g, '0$1');
将时间格式转成秒

const timeToNumber = (time) => time == 0 ? 0 : time.split(':').reverse().reduce((n, t, i) => n + (+t) * Math.pow(60, i) , 0);
将秒格式化成时间格式
export function numberToTime(seconds, guide = seconds) {
    seconds = seconds < 0 ? 0 : seconds;
    // let s = Math.floor(seconds % 60);
    let s = (seconds % 60).toFixed(2);
    let m = Math.floor(seconds / 60 % 60);
    let h = Math.floor(seconds / 3600);
    const gm = Math.floor(guide / 60 % 60);
    const gh = Math.floor(guide / 3600);

    // handle invalid times
    if (isNaN(seconds) || seconds === Infinity) {
        // '-' is false for all relational operators (e.g. <, >=) so this setting
        // will add the minimum number of fields specified by the guide
        h = m = s = '-';
    }

    // Check if we need to show hours
    h = (h > 0 || gh > 0) ? h + ':' : '';

    // If hours are showing, we may need to add a leading zero.
    // Always show at least one digit of minutes.
    m = (((h || gm >= 10) && m < 10) ? '0' + m : m) + ':';

    // Check if leading zero is need for seconds
    s = (s < 10) ? '0' + s : s;

    return h + m + s;
}