How to convert timestamp string to epoch time?

后端 未结 4 1467
离开以前
离开以前 2021-01-20 00:29

I have time stamp in format 2017-18-08 11:45:30.345.
I want to convert it to epoch time, so I am doing below:

String timeDateStr = \"2017         


        
4条回答
  •  野趣味
    野趣味 (楼主)
    2021-01-20 01:03

    Your code will fail for below 3 reasons.

    1. Your date string (2017-18-08 12:60:30.345), doesn't match with the Formatter you used. It should be yyyy-MM-dd HH:mm:ss.SSS instead of yyyy-dd-MM hh:mm:ss.SSS
    2. the range of minutes is (0-59), 60 doesn't come in this range.
    3. Even if you have corrected code based above point it won't run for ZonedDateTime. So you would need to create a LocalDateTime before and then pass a ZoneId to it.

    The code should look like below:

    String timeDateStr = "2017-18-08 12:59:30.345"; 
    DateTimeFormatter dtf  = DateTimeFormatter.ofPattern("yyyy-dd-MM HH:mm:ss.SSS");
    LocalDateTime date = LocalDateTime.parse(timeDateStr, dtf);
    ZonedDateTime     zdt  = date.atZone(ZoneId.of("Europe/London"));
    System.out.println(zdt.toInstant().toEpochMilli());
    

提交回复
热议问题