开发者

How to parse dates in GWT?

I lost a lot of time on this one, so I'm posting the question and answering from what I learned, as a resource to help other people out. The context of the problem is building an RSS reader. While RSS dates are supposed to conform to RFC822, they do so in differing ways so you want a method that's flexible. I tried to use GWT DateTimeFormat as well as hard-coding some different masks but kept finding testcases that broke my code. I finally stumbled upon the elegant solution:

Wrap a call to the javascript Date.parse() method. it really "just works".

As a meta-theory, which I'll try t开发者_运维百科o test as I continue with developing, there's a probably a lot of things that "just work" by using native javascript or perhaps other libraries out there rather than trying to brute force it using Java in GWT.

Cheers!


Use JSNI native javascript handling to wrap a call to the javascript Date.parse() method. It can handle a lot more formats than GWT's DateTimeFormat.

The code below gives a demo. Notice GWT disallows javascript passing long values around so I used toString to hack around that.

      public native String webDateToMilliSec(String webDate) /*-{
        var longDate = Date.parse(webDate);
        return longDate.toString();
      }-*/;

      public long getTimeStamp(final Element el) {
          String sDate = getValueIfPresent(el, "pubDate");
          String sLongDate = webDateToMilliSec(sDate);
          long longDate = Long.parseLong(sLongDate);
          return longDate;
      }
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜