0

I have a birthday (Date object) that I would like to convert to UTC time. I am able to use formatting to convert my locale time to UTC time by SimpleDatePattern. However when I format it, it converts the Date object to String. I tried parsing it (which returns a Date object) but converts it to local time system again. Here is my code below. Any help on converting the birthday field to UTC time while remaining a Date object and not a string?

public Date getBirthDay() {
    if (birthDay == null) {
        return null;
    }
    DateFormat utcFormat = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSS'Z'");
    utcFormat.setTimeZone(TimeZone.getTimeZone("UTC"));
    String formattedBirthDate = utcFormat.format(birthDay);
    try {
        System.out.println("I am here within try block" + utcFormat.parse(formattedBirthDate));
        birthDay = utcFormat.parse(formattedBirthDate);
    } catch (ParseException e) {
        e.printStackTrace();
    }
    return (Date) birthDay.clone();
}
Abra
  • 19,142
  • 7
  • 29
  • 41
iitrainii
  • 11
  • 3
  • If possible avoid using the old `java.util.Date` and instead use the new `java.time` framework. A good explanation on how to use it to convert from UTC to local time can be found here: https://stackoverflow.com/a/19632076/9712270 – magicmn Feb 04 '22 at 04:05
  • `java.util.Date` doesn't have a concept of time zone – MadProgrammer Feb 04 '22 at 04:07
  • @MadProgrammer `java.util.Date` actually does have a concept of time zone. Refer to [What's your time zone](https://www.infoworld.com/article/2073786/what-s-your-time-zone-.html) – Abra Feb 04 '22 at 04:16
  • @Abra `java.util.Date` in of itself does not have a time zone. All the formatting been done the class is based on other inputs around the current locale, this is (one of the many) issues with the API and why one should avoid using it, now that the `java.time` API exists. The document you point to is simply modifying the JVM's timezone, which the class would use to produce it's `toString` representation – MadProgrammer Feb 04 '22 at 05:07

0 Answers0