2

I have this method:

public Date parseDate(String dateStr) {
      try {
        SimpleDateFormat sdfSource = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.S z");
        return sdfSource.parse(dateStr);
      }
      catch(Exception e) {
        throw new RuntimeException("Error occurred while parsing date: " + dateStr);
      }
    }

And my unit test as below:

public void testEDTDate() throws Exception {
      DateFormatConverter converter = new DateFormatConverter();
      Date date = converter.parseDate("2009-09-15 15:28:20.0 EDT");   
      System.out.println("Converted Date: " + date.toString());
  }

The output is:

Wed Sep 16 02:28:20 ICT 2009

This cause to the unit test fail. The expected result is:

Tue Sep 15 15:28:20.0 EDT 2009

The format of output also wrong when it missing the second. How should I fix to display the Date as expected?

Barcelona
  • 2,122
  • 4
  • 21
  • 42

1 Answers1

3

When you parse the date using a given format, you cannot expect date.toString() to return the same format - they're unrelated.

You will need to use DateFormat#format(Date) in order to get a String in a given format, or you'll get whatever the system/implementation default is.

Romain
  • 12,679
  • 3
  • 41
  • 54
  • When I use DateFormat#format(Date) as you said but the result still the ICT timezone: 2009-09-16 02:28:20.0 ICT. I want to expect the result string as the given input – Barcelona Apr 24 '12 at 14:28
  • How about using `DateFormat#setTimeZone(TimeZone)`? – Romain Apr 24 '12 at 14:56