Java Date and Timestamp from instance of ZonedDateTime UTC

后端 未结 2 533
野性不改
野性不改 2020-12-14 02:10

I have a java application in which I would like the time in UTC. Currently, the code uses a mix of java.util.Date and java.sql.Timestamp. To get th

2条回答
  •  萌比男神i
    2020-12-14 03:09

    In Java, Date represents a point in time. It's not related to timestamp. When you call toString() method of a Date object, it converts that time to Platform's default Timestamp, e.g. Following will print date/time in UTC (as it sets default timezone to UTC):

    TimeZone.setDefault(TimeZone.getTimeZone("UTC"));
    ZonedDateTime zonedDateTime = ZonedDateTime.now(ZoneOffset.UTC);
    Timestamp timestamp = Timestamp.from(ZonedDateTime.now(ZoneOffset.UTC).toInstant());
    Date date = Date.from(ZonedDateTime.now(ZoneOffset.UTC).toInstant());
    System.out.println("ZonedDateTime: " + zonedDateTime);
    System.out.println("Timestamp: " + timestamp);
    System.out.println("Date: " + date);
    

提交回复
热议问题