如何将这种DateFormat“ 2020-05-29T11:40:55Z”转换为Date

时间:2020-06-04 08:22:49

标签: java android kotlin

我想将此“ 2020-05-29T11:40:55Z”传输到DateCalender,如果我像Date("2020-05-29T11:40:55Z")这样直接传输,则会引发错误出来。有人有想法吗? 而且,我的最低Android Api是19,因此禁止Java 8和Api26的大量api。

1 个答案:

答案 0 :(得分:2)

我不太了解您问题的最后一部分。您是说不能在项目中使用Java 8吗?对于基于Java 8的应用,请像这样使用ZonedDateTime

//1 - default pattern
String timeStamp = "2019-03-27T10:15:30";
ZonedDateTime localTimeObj = ZonedDateTime.parse(time);

//2 - specified pattern
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss a z");
String timeStamp1 = "2019-03-27 10:15:30 AM";
ZonedDateTime localTimeObj1 = ZonedDateTime.parse(timeStamp1, formatter);

//To get LocalDate from ZonedDateTime
LocalDate localDate = localTimeObj1.toLocalDate();

使用旧的方式获取日期:

    String DATE_FORMAT = "yyyy-MM-dd HH:mm:ss a";
    SimpleDateFormat formatter = new SimpleDateFormat(DATE_FORMAT);

    TimeZone tzInAmerica = TimeZone.getTimeZone("America/New_York");
    formatter.setTimeZone(tzInAmerica);

    String sDateInAmerica = formatter.format("2019-03-27 10:15:30 AM"); 
    //Create another simpledateformatter with your required format and use it to convert
    SimpleDateFormat formatter2 = new SimpleDateFormat(REQUIRED_DATE_FORMAT);
    Date date = formatter2.parse(sDateInAmerica);