How to convert ZonedDateTime to Date?

后端 未结 9 676
无人共我
无人共我 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:20

    Here is an example converting current system time to UTC. It involves formatting ZonedDateTime as a String and then the String object will be parsed into a date object using java.text DateFormat.

        ZonedDateTime zdt = ZonedDateTime.now(ZoneOffset.UTC);
        final DateTimeFormatter DATETIME_FORMATTER = DateTimeFormatter.ofPattern("yyyyMMdd HH:mm:ss");
        final DateFormat FORMATTER_YYYYMMDD_HH_MM_SS = new SimpleDateFormat("yyyyMMdd HH:mm:ss");
        String dateStr = zdt.format(DATETIME_FORMATTER);
    
        Date utcDate = null;
        try {
            utcDate = FORMATTER_YYYYMMDD_HH_MM_SS.parse(dateStr);
        }catch (ParseException ex){
            ex.printStackTrace();
        }
    

提交回复
热议问题