1
    protected static Date getZonedTime(Date time,ZoneId toZoneId) {
        
        System.out.println("***********************************************************************************");
        ZonedDateTime zdt = ZonedDateTime.ofInstant(Instant.ofEpochMilli(time.getTime()), ZoneId.of("UTC"));
        System.out.println(zdt);
        Date date = new Date(zdt.withZoneSameInstant(ZoneId.of("Asia/Kolkata")).toInstant().toEpochMilli());
        System.out.println(date);
        System.out.println("***********************************************************************************");
        return date;
    }
  • Why is this code behaving differently when run in local machine vs google cloud function ?

Objective of the code is to convert time to clients (of http request) timezone (time is retrieved from mysql where its stored in UTC)

Output in local JVM

input = 2020-09-01T16:54:20.704Z[UTC]

output = Tue Sep 01 22:24:20 IST 2020

Output from Google Cloud function

input = invoked getZonedTime=2020-09-01 15:10:31.0

output = returning getZonedTime=Tue Sep 01 15:10:31 UTC 2020

Was expecting the time at the new timezone (with the same instance of time of the date object passed) be returned.

Thanks

user1241724
  • 63
  • 1
  • 5
  • how does it behave locally v. on GCP? – Jhecht Sep 01 '20 at 17:15
  • 1
    I suggest editing the question to be more clear about what is actually happening with this code, and how it's different than what you expect. – Doug Stevenson Sep 01 '20 at 17:22
  • Done. Edited the question – user1241724 Sep 01 '20 at 17:27
  • Do you indispensably need an old-fashioned `Date` object? If you can, stick to classes from [java.time, the modern Java date and time API](https://docs.oracle.com/javase/tutorial/datetime/) like `ZonedDateTime` and `Instant`. The old ones are so poorly designed. – Ole V.V. Sep 01 '20 at 18:11
  • Contrary to a `ZonedDateTime` a `Date` hasn’t got a time zone. It’s just its `toString` method fooling you /and many others) by using the JVM’s default time zone setting for rendering the string it returns (`System.out.println(date)` implicitly calls `toString`). – Ole V.V. Sep 01 '20 at 18:13

0 Answers0