Sherlock123
Sherlock123

Reputation: 61

set timezone standard for java program

I have a junit test as stated below:

Calendar cal = somecode.getDate();
assertEquals("1941-02-31-05:00", cal.toString);

This passes in my local machine but in the sandbox due to timezone standard differences, the value of cal.toString() comes up as "1941-02-31Z". So, the assertion keeps failing. Does anyone know how I can make this pass in both the places without changing timezone standards or formats in either machines. May be just by setting a default time zone standard inside the code?

I cannot upgrade from Java 6. So, I need to find a solution inside the code.

Upvotes: 0

Views: 70

Answers (1)

Andy Turner
Andy Turner

Reputation: 140318

You can use the setTimeZone method to set the timezone to a particular value.

However, you also probably shouldn't be relying on the format of Calendar.toString():

This method is intended to be used only for debugging purposes, and the format of the returned string may vary between implementations.

You should probably check the fields individually, rather than relying upon the string:

cal.setTimeZone(...);
assertEquals(1941, cal.get(Calendar.YEAR));
assertEquals(2, cal.get(Calendar.MONTH));
// ... etc.

Upvotes: 2

Related Questions