【问题标题】:Format date with moment js library使用时刻 js 库格式化日期
【发布时间】:2014-02-04 06:32:13
【问题描述】:

我正在尝试在我的 GWT JSNI 代码中使用 moment js 库:

public native String momentNow(String date) /*-{
    $wnd.console.log("Date: " + date);
    return $wnd.moment("YYYY-MM-DD HH:mm Z", date).format();
}-*/;

使用示例输入:2014-02-04 07:47 +0800

但是,该方法返回的是“无效日期”字符串。我的代码可能有什么问题?

【问题讨论】:

  • 首先,你需要ZZ,而不是Z。其次,这是一个更大问题的迹象,因为我认为即使有 ZZ 也不起作用。
  • 你想做什么?这似乎很有趣。

标签: javascript momentjs


【解决方案1】:

嗯...这很奇怪:

这行得通:

moment("YYYY-MM-DD HH:mm ZZ", moment().format("YYYY-MM-DD HH:mm ZZ"))
moment("YYYY-MM-DD HH:mm ZZ", "2014-02-04 07:47 +0800")
+moment("YYYY-MM-DD HH:mm ZZ", "2014-02-04 07:47 +0800")

但这不起作用:

moment(
        "YYYY-MM-DD HH:mm ZZ", 
        moment().format("YYYY-MM-DD HH:mm ZZ")
      ).format()

这很有效:

moment( +moment("YYYY-MM-DD HH:mm ZZ", "2014-02-04 07:47 +0800") ).format()

那么这是一种解决方法吗?

【讨论】:

    【解决方案2】:

    您的参数顺序错误。根据the documentation,格式字符串应作为second 参数传递。

    moment(date, "YYYY-MM-DD HH:mm Z").format()
    

    但是,由于此格式是默认 ISO 字符串之一listed here,您可以省略它。

    moment(date).format()
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2019-10-02
      • 1970-01-01
      • 2020-01-14
      • 1970-01-01
      • 1970-01-01
      • 2021-09-15
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多