1

I am trying to convert GMT timestamp to local timestamp with particular timezone

This is what I have implemented

public static void test(Timestamp p_gmtTime, String p_timeZone) throws ParseException {
        SimpleDateFormat tzFormat = new SimpleDateFormat("MMM dd, yyyy HH:MM:SS a", Locale.ENGLISH);
        tzFormat.setTimeZone(TimeZone.getTimeZone(p_timeZone)); // Use whatever timezone
        tzFormat.format(p_gmtTime);
        //System.out.println(tzFormat.format(p_gmtTime)); // This line gives correct o/p
        
        Calendar calendar = tzFormat.getCalendar();
        
        //calendar.setTime(tzFormat.parse(format));
        System.out.println(calendar.getTime()); // this line gives wrong result
    }

Issue comes when there is daylight savings are on, then it gives future date instead of current date, lets say If I do transaction today 30-Dec-2021 it gives date of 31-Dec-2021 and I have limitation to use only calendar object. I need help in converting GMT Timestamp to local Timestamp with particular timezone

Doctor Who
  • 747
  • 1
  • 5
  • 28
  • 1
    Didn't we already do this? Stop using `Calendar`, `SimpleDateFormat` and, in general, the `java.util.Date` classes. Instead, make use of the `java.time` APIs instead, for [example](https://stackoverflow.com/questions/23263490/how-to-convert-java-sql-timestamp-to-localdate-java8-java-time) – MadProgrammer Dec 31 '21 at 02:26
  • yes but I have limitation to use only those classes. – Doctor Who Dec 31 '21 at 02:28
  • 1
    Any reason why are restricted to using (out-of-date and bug riddled) APIs? Could use one of the back port APIs? – MadProgrammer Dec 31 '21 at 02:29
  • Its a very old application and function is used from many other places, dont want to disturb other classes. – Doctor Who Dec 31 '21 at 02:31
  • 1
    If you're using Java 8+ you get `java.time` for free, otherwise, you're going to have to live with these (continuing) issues :P – MadProgrammer Dec 31 '21 at 02:32
  • I hope that this can give you a start if I understand the question, if not apologies. `LocalDateTime ldt = LocalDateTime.now(); ZoneId zone = ZoneId.systemDefault(); ZoneOffset zoneOffset = zone.getRules().getOffset(ldt); ZonedDateTime zdt = ldt.atOffset(zoneOffset) .atZoneSameInstant(ZoneId.of(timezone)); DateTimeFormatter dtf = DateTimeFormatter.ofPattern("yyyyMMddHHmm"); String date = dtf.format(zdt);` – Mike Croteau Dec 31 '21 at 03:02
  • `p_gmtTime.toInstant().atZone( ZoneId.of( p_timeZone ) ).toString()` – Basil Bourque Dec 31 '21 at 06:14

0 Answers0