On Jun 7, 7:58 pm, Rob Tanner <[email protected]> wrote:
> I have a Date() object that holds a date of birth and I want to
> extract the year and make sure no one's trying to tell me they're 150
> years old, etc.  The getYear method of the Date() class is deprecated
> and you normally use a Calendar() to get the year.  The problem is
> that when I try to use a Calendar() object the application doesn't
> know what it is.  How can I extract the year from a Date() object and
> not fall back on a deprecated method?

Sadly, the best method is to use GWT's DateTimeFormat:

private static final DateTimeFormat YEAR_FORMAT =
DateTimeFormat.getFormat("yyyy");
public static int year(final Date date) {
  return Integer.parseInt(YEAR_FORMAT.format(date));
}

You can put this into a utility class; you might even want to
remove the static modifier on year() and inject the class
where its needed; that might help testing.

Since GWT is being translated to JavaScript, and JS has no
threads, you can leave YEAR_FORMAT static, and you don't
need to synchronize access to it or create one for each
year() call.  Still, since you get the format through a getFormat()
call and not a constructor, I suspect GWT caches DateTimeFormats.
In that case the following is clearer.

public int year(Date date) {
  return
Integer.parseInt(DateTimeFormat.getFormat("yyyy").format(date));
}

Should we all be using [JG]oda-Time?

Respectfully,
Eric Jablow

-- 
You received this message because you are subscribed to the Google Groups 
"Google Web Toolkit" group.
To post to this group, send email to [email protected].
To unsubscribe from this group, send email to 
[email protected].
For more options, visit this group at 
http://groups.google.com/group/google-web-toolkit?hl=en.

Reply via email to