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?

1

1 Answer 1

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.

Sign up to request clarification or add additional context in comments.

2 Comments

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
How about using DateFormat#setTimeZone(TimeZone)?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.