How to convert ZonedDateTime to Date?

后端 未结 9 705
无人共我
无人共我 2020-12-04 09:19

I am trying to set a server agnostic date time in my database and I believe the best practice to do so is to set a UTC DateTime. My db server is Cassandra and the db driver

9条回答
  •  刺人心
    刺人心 (楼主)
    2020-12-04 10:18

    I use this.

    public class TimeTools {
    
        public static Date getTaipeiNowDate() {
            Instant now = Instant.now();
            ZoneId zoneId = ZoneId.of("Asia/Taipei");
            ZonedDateTime dateAndTimeInTai = ZonedDateTime.ofInstant(now, zoneId);
            try {
                return new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").parse(dateAndTimeInTai.toString().substring(0, 19).replace("T", " "));
            } catch (ParseException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
            return null;
        }
    }
    

    Because Date.from(java.time.ZonedDateTime.ofInstant(now, zoneId).toInstant()); It's not work!!! If u run your application in your computer, it's not problem. But if you run in any region of AWS or Docker or GCP, it will generate problem. Because computer is not your timezone on Cloud. You should set your correctly timezone in Code. For example, Asia/Taipei. Then it will correct in AWS or Docker or GCP.

    public class App {
        public static void main(String[] args) {
            Instant now = Instant.now();
            ZoneId zoneId = ZoneId.of("Australia/Sydney");
            ZonedDateTime dateAndTimeInLA = ZonedDateTime.ofInstant(now, zoneId);
            try {
                Date ans = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").parse(dateAndTimeInLA.toString().substring(0, 19).replace("T", " "));
                System.out.println("ans="+ans);
            } catch (ParseException e) {
            }
            Date wrongAns = Date.from(java.time.ZonedDateTime.ofInstant(now, zoneId).toInstant());
            System.out.println("wrongAns="+wrongAns);
        }
    }
    

提交回复
热议问题