【问题标题】:Preserve Object type when using moment.format()使用 moment.format() 时保留对象类型
【发布时间】:2021-11-20 18:09:02
【问题描述】:

我正在使用矩库将字符串转换为日期,如下所示:

var time = moment.parseZone("2021-09-28T12:00:00-07:00");

结果是:2021 年 9 月 28 日星期二 12:00:00 GMT-0700

但是如果我格式化这个:

var time = moment.parseZone("2021-09-28T12:00:00-07:00").format();

这会将“时间”转换为字符串,因此我无法在网格中将其作为日期进行操作,我该如何实现这一点以便对日期进行排序并以某种格式显示?

注意:如果我使用 time.toDate(),它会将偏移量更改为我的本地并且需要保留它。

【问题讨论】:

  • 您不能设置Date 对象的时区(或偏移量)。因此,您需要操纵网格库的排序方法以按时刻日期或其他库的排序。

标签: javascript momentjs offset


【解决方案1】:

对日期数组进行排序。您可能需要翻转您的 diff 订单才能获得正确的排序顺序。

// 'a' and 'b' are expected to be date objects
// Since your strings are full ISO 8601, you
// shouldn't require additional parsing
const array = stringArray.map(it => new Date(it));
const sortedArray = array.sort((a, b) => {
  const mA = moment(a);
  const mB = moment(b);
  return mA.diff(mB) // or mB.diff(mA), depending on order
})

【讨论】:

    猜你喜欢
    • 2011-07-02
    • 2020-09-15
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-05-03
    • 2010-10-17
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多