Convert String to Joda LocalTime format (HH:mm:ss) and Remove milliseconds

后端 未结 3 1764
遇见更好的自我
遇见更好的自我 2021-01-18 03:45
DateTimeFormatter fmt = DateTimeFormat.forPattern(\"HH:mm:ss\");
LocalTime localTime = fmt.parseLocalTime(\"02:51:20\");
System.out.println(\"LocalTime:            \         


        
相关标签:
3条回答
  • 2021-01-18 04:16

    Yes - you just need to format when you print out. Currently you're just using the default toString() representation. If you're happy with the formatter you've already got, you can just use:

    System.out.println("LocalTime:            " + fmt.print(localTime));
    
    0 讨论(0)
  • 2021-01-18 04:22

    Fixed this using

    DateTime time = new DateTime();
    DateTimeFormatter format = DateTimeFormat.forPattern("HH:mm:ss");
    String localTime = time != null ? format.print(new LocalTime(time.getHourOfDay(), 
    time.getMinuteOfHour(), time.getSecondOfMinute())) : null;
    

    DateTime and LocalTime are from joda

    0 讨论(0)
  • 2021-01-18 04:28

    You can easily use your DateTimeFormetter print() method. Try like this;

        DateTimeFormatter fmt = DateTimeFormat.forPattern("HH:mm:ss");
        LocalTime localTime = fmt.parseLocalTime("02:51:20");
        System.out.println("LocalTime                        :  " + localTime);
        System.out.println("LocalTime with DateTimeFormatter :  " + fmt.print(localTime));
    

    And the output is;

    LocalTime                        :  02:51:20.000
    LocalTime with DateTimeFormatter :  02:51:20
    
    0 讨论(0)
提交回复
热议问题