Skip to content

Instantly share code, notes, and snippets.

@dardison
Created September 1, 2015 16:24
Show Gist options
  • Save dardison/b53018253d7a4be0116e to your computer and use it in GitHub Desktop.
Save dardison/b53018253d7a4be0116e to your computer and use it in GitHub Desktop.
An implementation of DateTimeFormat compatible in Client & Server for GWT
public abstract class DateTimeFormat {
static DateTimeFormat getFormat(String pattern)
{
if (GWT.isClient())
return new DateTimeFormatClient(pattern);
else
return new DateTimeFormatServer(pattern);
}
public abstract String format(Date date);
public abstract Date parse(String dateString);
@GwtCompatible
private static class DateTimeFormatClient extends DateTimeFormat
{
protected String pattern;
public DateTimeFormatClient(String pattern)
{
this.pattern = pattern;
}
public String format(Date date)
{
return com.google.gwt.i18n.client.DateTimeFormat.getFormat(pattern).format(date);
}
public Date parse(String stringDate){
return com.google.gwt.i18n.client.DateTimeFormat.getFormat(pattern).parseStrict(stringDate);
}
}
private static class DateTimeFormatServer extends DateTimeFormatClient
{
public DateTimeFormatServer(String pattern)
{
super(pattern);
}
@GwtIncompatible("Server format")
public String format(Date date)
{
return (new java.text.SimpleDateFormat(pattern)).format(date);
}
@GwtIncompatible("Server parse")
public Date parse(String dateString){
try{
return (new java.text.SimpleDateFormat(pattern)).parse(dateString);
}catch(Exception ex){
throw new IllegalArgumentException("No se puede convertir a fecha: "+ dateString);
}
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment