【问题标题】:How to get years and months with momentjs and vuejs如何使用 momentjs 和 vuejs 获得年和月
【发布时间】:2018-08-27 17:03:00
【问题描述】:

我正在尝试使用 momentjs 格式显示相对时间:

年和月,即 2 年零 8 个月

目前,2016-01-29 | moment('from', 'now', true) 最多只能四舍五入到 3 年。

vue-moment package 没有直接的方法,momentjs 似乎也没有处理这个问题

我也尽量不使用任何额外的插件。

【问题讨论】:

  • 抱歉,您将无法使用momentjs 完成此操作。您需要自己处理转换。计算月数,然后取模 x%12 到 gen 月和 Math.floor(x/12) 到年。然后将其添加到指令或插件中以使其可访问。
  • @Daniel 感谢您的回复。我曾想象我必须这样做,但认为有一个直接的实现

标签: vue.js momentjs vuetify.js


【解决方案1】:

您可以将时刻计算分解为毫秒。

let fromTime = moment("2016-01-29").diff(moment(), "milliseconds")

然后使用提供的差异创建一个持续时间对象。

let duration = moment.duration(fromTime)

它将返回一个持续时间对象,该对象将具有毫秒、秒、分钟、小时、天、月和年的方法。

duration.methods() 方法返回负值,这就是为什么要除以负值 / -1 来将值转换为正值。

这是使用duration.years()duration.months() 的示例

let timeString = duration.years() / -1 + " years and " + duration.months() / -1 + " months"

所以现在timeString 将返回2 years and 6 months

【讨论】:

  • 也试试这个
  • 这按预期工作!我添加了一些小调整作为将来参考的答案
【解决方案2】:

//导入时刻

var moment = require('moment')

// 将此作为方法添加到您的组件中

 getYearsMonthsDays(date){
        let fromTime = moment(date).diff(moment(), "milliseconds")
        let duration = moment.duration(fromTime)
        let years = duration.years() / -1
        let months = duration.months() / -1
        let days = duration.days() / -1
        if (years > 0) {
            var Ys = years == 1? years + " year and ": years + " years and "
            var Ms = months == 1? months + " month": months + " months"
            return Ys + Ms
        } else {
            if (months > 0)
                return months == 1? months + " month": months + " months"
            else
                return days == 1? days + " day": days + " days"
        }
    }

//在组件中的使用

{{ getYearsMonthsDays(date) }}

通过@jordanw 的响应进行调整,这可以按预期工作。 也许它可以做得更短或更好,但这没问题。

【讨论】:

    【解决方案3】:

    这是一个使用 date-fns ans 创建自定义过滤器的版本

    https://codesandbox.io/s/mmm0q9r61x

    这是过滤器本身的代码

    import Vue from "vue";
    import { differenceInMonths, differenceInYears } from "date-fns";
    
    Vue.filter("tsDiff", (from, to) => {
      const tsTo = to || new Date();
      try {
        // return `${distanceInWords(from, tsTo)}`;
        let y = differenceInYears(from, tsTo);
        let m = differenceInMonths(from, tsTo) - y * 12;
        let r = [];
        if (y !== 0) {
          r.push(`${Math.abs(y)} Year${Math.abs(y) !== 1 ? "s" : ""}`);
        }
        if (m !== 0) {
          r.push(`${Math.abs(m)} Month${Math.abs(m) !== 1 ? "s" : ""}`);
        }
        r = r.join(" and ");
        if (y < 0 || m < 0) {
          r = r + " ago";
        } else {
          r = "In " + r;
        }
        return r;
      } catch (error) {
        // eslint-disable-next-line
        console.error(error);
        return "Invalid Date";
      }
    });
    

    一旦您导入过滤器 (import './datefilter';),您就可以在任何地方拨打 {{ myDate | tsDiff }}

    您可以根据需要调整使用。

    您可以轻松地将 differenceInYearsdifferenceInMonths 的使用替换为 vanilla js,这样您就完全不需要依赖了。

    附带说明一下,看看是否可以用 date-fns 替换 momentjs。 Momentjs 是一个不错的库,但无论你使用多少,你都必须加载整个库。但是,当您使用 Date-fns 时,您可以指定要使用的部分,并且只有那些被注入到最终构建中。这可以大大节省最终构建大小。

    【讨论】:

    • 谢谢。这可能有效,但正如我所说,不尝试使用任何其他库只是 momentjs
    • 你可以使用 moment js 进行小的改动。将 differenceInYears 替换为 moment().diff(from, 'years'); 并类似地替换为 differenceInMonths
    猜你喜欢
    • 1970-01-01
    • 2020-12-08
    • 2011-06-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-02-07
    • 1970-01-01
    • 2016-01-25
    相关资源
    最近更新 更多