0

I have the following Java variable:

@JsonProperty
@Temporal(TemporalType.TIMESTAMP)
@Column(name = "start")
private Calendar start;

Of format:

"yyyy-MM-dd HH:mm:ss"

I recieve this field in UTC, but want to convert this field to EST time. how can I do so?

I am trying to do so as follows:

private Calendar convertToEST(Calendar calendar) {

        LocalDateTime ldt = LocalDateTime.parse(convertCalendarToString(calendar), DateTimeFormatter.ofPattern(DATE_FORMAT));
        
        ZonedDateTime estZonedDateTime = ldt.atZone(ZoneId.of("EST"));
        
        ZonedDateTime convertedZonedDateTime = estZonedDateTime.withZoneSameInstant(ZoneId.of("EST"));

        Date convertedDate = Date.from(convertedZonedDateTime.toInstant());

        return toCalendar(convertedDate);
    }

    public static Calendar toCalendar(Date date){
        Calendar cal = Calendar.getInstance();
        cal.setTime(date);
        return cal;
    }

    private static String convertCalendarToString(Calendar calendar) {
        return dateFormat.format(calendar.getTime());
    }
java12399900
  • 1,449
  • 6
  • 17
  • 39
  • 2
    Why do you have a `Calendar` here and not just a date? And why not use the `java.time` API? In any case, if you want to convert the point in time represented by that calendar to a string representation use `Calendar.toInstant()` and `DateTimeFormatter`. – Thomas Jul 20 '21 at 12:58
  • I recommend you don’t use `Calendar` and `Date`. Those classes are poorly designed and long outdated. Stick to `ZonedDateTime` from [java.time, the modern Java date and time API](https://docs.oracle.com/javase/tutorial/datetime/). Also a `Calendar` hasn’t got a format, so I don’t uunderstand what you mean woth that part. – Ole V.V. Jul 23 '21 at 02:48
  • `ZoneId.of("EST")` throws a `java.time.zone.ZoneRulesException: Unknown time-zone ID: EST`. Use a proper time zone ID in the *region/city* format, for example America/Montreal or America/New_York. – Ole V.V. Jul 23 '21 at 03:36

0 Answers0