GWT: use DateTimeFormat on client and SimpleDateFormat on server

后端 未结 5 838
无人及你
无人及你 2020-12-17 09:34

I have a function that must work the same way on both client and server and it formats dates.

if (GWT.isClient())
{
  // Use DateTimeFormat
} else {
  // Use         


        
5条回答
  •  谎友^
    谎友^ (楼主)
    2020-12-17 10:07

    You can use com.google.gwt.i18n.shared.DateTimeFormat on both server and client:

    Call the protected constructor to avoid GWT.create

    String pattern = "yyyyMMdd"; /*your pattern here*/ 
    DefaultDateTimeFormatInfo info = new DefaultDateTimeFormatInfo();
    DateTimeFormat dtf = new DateTimeFormat(pattern, info) {};  // <= trick here
    

    Example

    Date d = dtf.parse("20120301");
    CalendarUtil.addDaysToDate(d, -1);
    String s = dtf.format(d);
    // s now contains "20120229"
    

    The trick is done by extending the DateTimeFormat so we can use protected constructor with DateTimeFormatInfo where we use the new DefaultDateTimeFormatInfo() to avoid calling of GWT.create

提交回复
热议问题