使用date-fns格式化持续时间(从秒开始)

时间:2018-02-13 21:43:10

标签: date-fns

给定int值1807,使用date-fns格式化为30:07

是的,我知道这可以通过vanilla js实现,但是这可以使用date-fns吗?

6 个答案:

答案 0 :(得分:10)

根据 date-fns/date-fns#229 (comment) 中的示例代码,我们现在可以使用 intervalToDuration 将秒转换为 Duration,然后可以根据 OP 的需要简化格式:

import {  intervalToDuration } from 'date-fns'

const seconds = 10000

intervalToDuration({ start: 0, end: seconds * 1000 })
// { hours: 2, minutes: 46, seconds: 40 }

所以为了 OP 的需要:

import {  intervalToDuration } from 'date-fns'

const seconds = 1807
const duration = intervalToDuration({ start: 0, end: seconds * 1000 })
// { minutes: 30, seconds: 7 }

const formatted = `${duration.minutes}:${duration.seconds}`

答案 1 :(得分:2)

您可以通过简单修改中间帮助日期使用date-fns来完成此操作。使用new Date( 0 ),您将获得日期设置为1970年1月1日00:00:00 UTC。然后,您可以使用date-fns中的addSeconds添加相关秒数(实际上您可以使用本机日期setTime( 1000 * seconds ))。格式化分钟和秒数将为您提供所需的结果。



var input = document.getElementById('seconds');
var output = document.getElementById('out');

output.innerText = formattedTime(input.value);
input.addEventListener('input', function() {
  output.innerText = formattedTime(input.value);
});

function formattedTime(seconds) {
  var helperDate = dateFns.addSeconds(new Date(0), seconds);
  return dateFns.format(helperDate, 'mm:ss');
}

<script src="https://cdnjs.cloudflare.com/ajax/libs/date-fns/1.26.0/date_fns.min.js"></script>

<input type="number" id="seconds" value="1807">
<pre id="out"></pre>
&#13;
&#13;
&#13;

答案 2 :(得分:2)

这是简单的实现:

import distanceInWords from 'date-fns/distance_in_words'

const duration = s => distanceInWords(0, s * 1000, { includeSeconds: true })

duration(50) // 'less than a minute'
duration(1000) // '17 minutes'

这基本上与:

import moment from 'moment'    

const duration = s => moment.duration(s, 'seconds').humanize()

duration(50) // 'a minute'
duration(1000) // '17 minutes'

答案 3 :(得分:2)

此功能会将秒转换为持续时间格式hh:mm:ss,其模拟持续时间在moment.js中

import { addHours, getMinutes, getHours, getSeconds } from 'date-fns';

export const convertToDuration = (secondsAmount: number) => {
    const normalizeTime = (time: string): string =>
    time.length === 1 ? `0${time}` : time;

    const SECONDS_TO_MILLISECONDS_COEFF = 1000;
    const MINUTES_IN_HOUR = 60;

    const milliseconds = secondsAmount * SECONDS_TO_MILLISECONDS_COEFF;

    const date = new Date(milliseconds);
    const timezoneDiff = date.getTimezoneOffset() / MINUTES_IN_HOUR;
    const dateWithoutTimezoneDiff = addHours(date, timezoneDiff);

    const hours = normalizeTime(String(getHours(dateWithoutTimezoneDiff)));
    const minutes = normalizeTime(String(getMinutes(dateWithoutTimezoneDiff)));
    const seconds = normalizeTime(String(getSeconds(dateWithoutTimezoneDiff)));

    const hoursOutput = hours !== '00' ? `${hours}:` : '';

    return `${hoursOutput}${minutes}:${seconds}`;
};

答案 4 :(得分:0)

在“ date-fns”的新版本中,distanceInWords现在称为formatDistance

所以代码是:

export const formatSecondsDuration = (seconds: number) =>
  formatDistance(0, seconds * 1000, { includeSeconds: true })

答案 5 :(得分:0)

日期-fns中似乎不直接等于moment.duration ...

我编写的此功能可能会对某人有所帮助。 Date-fns。differenceInSeconds用于获取以秒为单位的总差异。有等效的毫秒,分钟等方法。 然后我使用香草js数学来格式化

/**
* calculates the duration between two dates.
* @param {date object} start The start date.
* @param {date object} finish The finish date.
* @return {string} a string of the duration with format 'hh:mm'
*/
export const formatDuration = (start, finish) => {
    const diffTime = differenceInSeconds(finish, start);
    if (!diffTime) return '00:00'; // divide by 0 protection
    const minutes = Math.abs(Math.floor(diffTime / 60) % 60).toString();
    const hours = Math.abs(Math.floor(diffTime / 60 / 60)).toString();
    return `${hours.length < 2 ? 0 + hours : hours}:${minutes.length < 2 ? 0 + minutes : minutes}`;
};