Yes dealing with time is always one good source of confusion. If you deal with financial application, many uses New York City as a guideline. A trading platform I’m working at on a daily basis uses NY+7 time zone such that 5pm in New York coincide with midnight. This is how you can format current NY+7 time (keep in mind USA do have DST and your local time zone might/not have it):
TimeZone nyPlus7 = TimeZone.getTimeZone("America/New_York"); nyPlus7.setRawOffset(nyPlus7.getRawOffset() + 7*3600*1000); DateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); df.setTimeZone(nyPlus7); String nyPlus7TimeNow = df.format(new Date());
And here’s a unit test proof the above method indeed works:
String pattern = "yyyy-MM-dd HH:mm:ss"; Date expected, actual; // Setup UTC and NY+7 time zones TimeZone utcTz = TimeZone.getTimeZone("UTC"); TimeZone nyp7Tz = TimeZone.getTimeZone("America/New_York"); nyp7Tz.setRawOffset(nyp7Tz.getRawOffset() + 7*3600*1000); // Setup DateFormat for parsing DateFormat utc = new SimpleDateFormat(pattern); utc.setTimeZone(utcTz); DateFormat nyp7 = new SimpleDateFormat(pattern); nyp7.setTimeZone(nyp7Tz); // US DST off, NY is UTC-5, NY+7 is UTC+2 expected = utc.parse("2014-03-09 06:59:59"); actual = nyp7.parse("2014-03-09 08:59:59") Assert.assertEquals(expected, actual); // US DST on, NY is UTC-4, NY+7 is UTC+3 expected = utc.parse("2014-03-09 07:00:00"); actual = nyp7.parse("2014-03-09 10:00:00") Assert.assertEquals(expected, actual);
It’s important to understand the best practice is to never store time data in string. Stick to java Date object or alike. Only format your time to string whenever you need to present it visually