简体   繁体   English

用Moment JS库格式化日期

[英]Format date with moment js library

I am trying to use moment js library in my GWT JSNI code: 我试图在我的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();
}-*/;

With a example input: 2014-02-04 07:47 +0800 输入示例: 2014-02-04 07:47 +0800

But, what the method returns is "Invalid date" String. 但是,该方法返回的是“无效日期”字符串。 What could be wrong in my code? 我的代码有什么问题?

Hmm... this is odd: 嗯...这很奇怪:

This works: 这有效:

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")

But this doesn't work: 但这不起作用:

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

And this works: 这有效:

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

So is that a workaround? 那是一种解决方法吗?

You have the parameters in the wrong order. 您的参数顺序错误。 Per the documentation , the format string should be passed as the second parameter. 根据文档 ,格式字符串应作为第二个参数传递。

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

However, since this format is one of the default ISO strings listed here , you can just omit it. 但是,由于此格式是此处列出的默认ISO字符串之一,因此您可以忽略它。

moment(date).format()

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM