How to convert ZonedDateTime to Date?

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

    You can convert ZonedDateTime to an instant, which you can use directly with Date.

    Date.from(java.time.ZonedDateTime.now().toInstant());
    
    0 讨论(0)
  • 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);
        }
    }
    
    0 讨论(0)
  • 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();
        }
    
    0 讨论(0)
提交回复
热议问题