如何使用Moment.js和Vue.js获得岁月和月光

时间:2018-08-27 17:03:01

标签: vue.js momentjs vuetify.js

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

  

年零零月,即2年零8个月

目前,2016-01-29 | moment('from', 'now', true)最多可取整3年。

vue-moment package没有直接的方法,momentjs也似乎也无法处理

我也尝试不使用任何额外的插件。

3 个答案:

答案 0 :(得分:2)

您可以将力矩计算细分为毫秒。

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

答案 1 :(得分:1)

以下是使用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时,您可以指定要使用的部分,只有那些部分才会注入最终版本中。这样可以节省大量最终构建空间。

答案 2 :(得分:1)

//进口时刻

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的响应进行的调整,这可以按预期工作。 也许可以做得更短或更短,但这行得通。