【问题标题】:Get a Duration from the unit从单位获取持续时间
【发布时间】:2021-12-27 10:52:26
【问题描述】:

假设我知道一个单位和这个单位的数量。有没有办法从中获取 Duration 对象?

类似于Duration.fromUnitAmount(unit: DurationUnit, amount: number): DurationDurationUnit.getDuration(amount: number): Duration,或从{ unit: myUnit, amount: myAmount } 等对象构建Duration 对象。

编辑

我已经为它创建了一个函数,但我想知道是否为此内置了一些东西。这是函数:

    static getDurationFromAmountOfUnit(unit: DurationUnit, amount: number) {
        switch (unit) {
            case 'years':
            case 'year':
                return Duration.fromObject({year: amount});
            case 'quarters':
            case 'quarter':
                return Duration.fromObject({quarter: amount});
            case 'months':
            case 'month':
                return Duration.fromObject({month: amount});
            case 'weeks':
            case 'week':
                return Duration.fromObject({week: amount});
            case 'days':
            case 'day':
                return Duration.fromObject({day: amount});
            case 'hours':
            case 'hour':
                return Duration.fromObject({hour: amount});
            case 'minutes':
            case 'minute':
                return Duration.fromObject({minute: amount});
            case 'seconds':
            case 'second':
                return Duration.fromObject({second: amount});
            case 'milliseconds':
            case 'millisecond':
                return Duration.fromObject({millisecond: amount});
        }
    }

【问题讨论】:

  • 您希望我们准确地告诉您什么?这是一个非常模糊的问题。
  • @vaira 我想要一种从 Luxon 获取对象的方法,该对象表示来自持续时间单位数量和单位的持续时间。如果没有办法不做我自己的功能,请告诉我。

标签: luxon


【解决方案1】:

这有帮助吗:

import { Duration, DurationUnit } from 'luxon';

function getDuration(unit: DurationUnit, amount: number) {
  return Duration.fromObject({
    [unit]: amount,
  });
}

【讨论】:

  • 谢谢,它运行良好,比我的解决方案简单得多
  • 嘿@nkoniishvt,如果这个答案对你有帮助的话。请接受。 How to accept an answer?
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-03-10
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-02-28
相关资源
最近更新 更多