Search code examples
javapostgresqlamazon-web-servicesamazon-lightsailamazon-linux

Deployed application picking Universal time Instead of Local time on AWS Server


Currently, My AWS instance showing below time

timedatectl status
            **Local time:** Thu 2019-12-26 19:41:51 IST
            Universal time: Thu 2019-12-26 14:11:51 UTC
            RTC time: Thu 2019-12-26 14:11:51
            Time zone: Asia/Kolkata (IST, +0530)
       System clock synchronized: yes
       systemd-timesyncd.service active: yes
       RTC in local TZ: no

Pojo

@Entity
@Table(name = "hotel_booking")
public class Booking implements Serializable {

    private static final long serialVersionUID = 1L;

    @Id
    private Long id;

    @Id
    private Integer version;

    @NotNull
    @Column(name = "ota_reference_no", nullable = false)
    private String referenceNo;

    @Column(name = "guest_name")
    private String guestName;

    @Column(name = "created_date", columnDefinition = "timestamp", nullable = false)
    private LocalDateTime createdDate;

    @Column(name = "modified_date", columnDefinition = "timestamp")
    private LocalDateTime modifiedDate;

======

Once persist createdDate filed picking Universal time but required is, Local time.

The same getting expected result in localhost:

The database uses: Postgres (i.e. installed locally on the AWS instance)


Solution

  • Do yourself a favor if this is (or will become) a real application, and persist any actual points on the timeline (or real moments) always in UTC — you can actually get this straight in your application using the Instant type. Down the line, you can use ZonedDateTime (or LocalDateTime, but this one is tricky) to "translate" the values accordingly before exposing it to the user-agents — or for any other operation(s) you might be doing that could be time zone sensitive.

    By the way, the reason you are getting the Universal time instead of Local time it is because the Java Virtual Machine, the application, the framework you are using for persistence (or a combination) is/are set in such way, either by default, or because somewhere in the application there is a setting like this: -Duser.timezone=UTC. If it's the application, it might be ZoneOffset.UTC or TimeZone.setDefault(...), but these are unlikely as you would need to do this programmatically. Execute a System.out.println(ZoneId.systemDefault()), it should yield UTC (or something around those lines).