Convert string into LocalDateTime

前端 未结 4 485
滥情空心
滥情空心 2020-11-30 15:12

I have the following String:

18/07/2019 16:20

I try to convert this string into LocalDateTime with the following code:

<         


        
相关标签:
4条回答
  • 2020-11-30 15:44

    I think this will answer your question:

    val stringDate = expiration_button.text.toString()
    val formatter = DateTimeFormatter.ofPattern("dd/MM/yyyy hh:mm");
    val dt = LocalDate.parse(stringDate, formatter);
    

    Edit 1:

    It's probably crashing because you are using a 12hr Hour, instead of a 24hr pattern.

    Changing the hour to 24hr pattern by using a capital H should fix it:

    val dateTime = LocalDateTime.parse(stringDate, DateTimeFormatter.ofPattern("dd/MM/yyyy HH:mm"));
    
    0 讨论(0)
  • 2020-11-30 15:45

    You may try using "-" instead of "/" on the date.

    0 讨论(0)
  • 2020-11-30 16:02

    Change your datetime format to "dd/MM/yyyy hh:mm a" and provide a string date with additional AM/PM information, e.g. val stringDate = "18/07/2019 04:20 PM" or just use the 24 hour format "dd/MM/yyyy HH:mm".

    0 讨论(0)
  • 2020-11-30 16:10

    Use below to convert the time from String to LocalDateTime, but make sure you are getting the time in String form.

    String str = "2016-03-04 11:30";
    DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm");
    LocalDateTime dateTime = LocalDateTime.parse(str, formatter);
    

    Btw, If your String contains seconds as well like "2016-03-04 11:30: 40", then you can change your date time format to yyyy-MM-dd HH:mm:ss" as shown below:

    String str = "2016-03-04 11:30: 40";
    DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
    LocalDateTime dateTime = LocalDateTime.parse(str, formatter);
    
    0 讨论(0)
提交回复
热议问题