I am converting time from GMT to different USA time-zones. For that, I have written a method which is returning the 1-hour prior time. if the time is 2:00 clock it's returning 1:00 clock

private static Date timeFormat(String timeZone) throws ParseException { SimpleDateFormat sdfDate = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); DateFormat gmtFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); gmtFormat.setTimeZone(TimeZone.getTimeZone(TimeZone.getDefault().getID())); Date date = null; try { date = gmtFormat.parse(sdfDate.format(new Date())); LOG.info("GMT format time and date ==>> "+date); } catch (ParseException e) { e.printStackTrace(); } DateFormat pstFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); pstFormat.setTimeZone(TimeZone.getTimeZone(timeZone)); String timedd = pstFormat.format(date); LOG.info("Return the new time based on timezone : "+pstFormat.format(date)); return gmtFormat.parse(timedd); } 

Can anybody help me out what exactly is the issue, because a few months back the same method was working fine? Is it happening because of daylight saving time?

3

2 Answers

This can be done in a much simpler way using java.time APIs. Use Instant to represent the time in UTC. It can be converted to time at any zone, and formatted to a particular pattern.

DateTimeFormatter format = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss"); Instant now = Instant.now(); ZonedDateTime dt = now.atZone(ZoneId.of("UTC-05:00")); System.out.println(dt.format(format)); //2017-05-24 04:51:03 ZonedDateTime pstDate = now.atZone(ZoneId.of("UTC-07:00")); System.out.println(pstDate.format(format)); //2017-05-24 02:51:03 
4

After so much of digging i have found that TimeZone won't give correct result on basis of time-zone

(EST, CST, MST, PST)

so in my method the param which i have passed as timeZone was coming as a

(EST, CST, MST, PST)

Instead of EST, CST, MST, PST i have passed US/Eastern US/Pacific US/Mountain US/Central, and it worked fine for me

Your Answer

Sign up or log in

Sign up using Google Sign up using Facebook Sign up using Email and Password

Post as a guest

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy