Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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 to 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!

like image 288
glebk Avatar asked Jul 21 '10 04:07

glebk


1 Answers

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;
      }
like image 65
glebk Avatar answered Sep 24 '22 16:09

glebk