Search code examples
javadategwtsmartgwt

Parsing Date Adds One Day to Formatted Date


This simple code translates a Date string to the format I desire. However, when the date is formatted, an additional day is added. The parsing is done when the onChanged event fires on a RelativeDateItem control in SmartGWT. I do not think the use of that component effects the date parsing, however.

private static String DATE_FORMAT = "dd.MMM.yyyy kk:mm";
...
private void changeDateFormat()
{      
     DateUtil.setShortDatetimeDisplayFormatter(new DateDisplayFormatter()
     {
        public String format(Date date)
        {
           System.out.println("setShortDatetimeDisplayFormatter = " + date.toString());
           if(date == null)
           {
              return null;
           }
           else
           {
              final DateTimeFormat dateFormatter = DateTimeFormat.getFormat(DATE_FORMAT);
              System.out.println("Formatted date = " + dateFormatter.format(date));
              return dateFormatter.format(date);
           }

        }
     });

     // It is a requirement that we implement a custom date parser or the onChanged event
     // will not fire.

     DateUtil.setDateParser(new DateParser()
     {
        public Date parse(String dateString)
        {           
           System.out.println("Entering parse = " + dateString);
           final DateTimeFormat format = DateTimeFormat.getFormat(DATE_FORMAT);

           System.out.println("Exiting parse = " + format.parse(dateString));
           return format.parse(dateString);

        }
     });
  }

Debug:

setShortDatetimeDisplayFormatter = Tue Feb 19 00:00:00 EST 2013
Formatted date = 19.Feb.2013 24:00
Entering parse = 19.Feb.2013 24:00
Exiting parse = Wed Feb 20 00:00:00 EST 2013
Entering parse = 19.Feb.2013 24:00
Exiting parse = Wed Feb 20 00:00:00 EST 2013
setShortDatetimeDisplayFormatter = Wed Feb 20 00:00:00 EST 2013
Formatted date = 20.Feb.2013 24:00

It fires twice because the RelativeDateItem control contains both the picker text and the adjacent label text, so both have to be formatted.


Solution

  • Use this format:

    dd.MMM.yyyy HH:mm
    

    It looks like kk is unsymmetrical for format & parse. I never realised that before.

    But then nothing surprises me about Java's date handling any more...