提问者:小点点

尽管格式化程序模式(java.time)[duplicate],但没有打印零秒


我把12小时的时尚时间转换成24小时。 问题是,当秒数为“00”时,它们不会被打印出来,而不管格式化模式如何。 为什么会出现这种情况,如何打印零秒?

public static void main(String[] args) {
        String time_1 = "07:05:40PM";
        String time_2 = "07:05:00PM";

        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("hh:mm:ssa");

        System.out.println("time_1 " + LocalTime.parse(time_1, formatter));
        System.out.println("time_2 " + LocalTime.parse(time_2, formatter));
    }

输出为:

time_1 19:05:40
time_2 19:05

共1个答案

匿名用户

使用DateTimeFormatterBuilder#ParseCaseInsensitive以不区分大小写的方式解析时间。 另外,请确保使用适当的格式打印时间。

照做

import java.time.LocalTime;
import java.time.format.DateTimeFormatter;
import java.time.format.DateTimeFormatterBuilder;

public class Main {
    public static void main(final String[] args) {
        String time_1 = "07:05:40PM";
        String time_2 = "07:05:00PM";

        //12-hour format
        DateTimeFormatter formatter1 = new DateTimeFormatterBuilder()
                .parseCaseInsensitive()
                .appendPattern("hh:mm:ssa")
                .toFormatter();
        
        //24-hour format
        DateTimeFormatter formatter2 = new DateTimeFormatterBuilder()
                .parseCaseInsensitive()
                .appendPattern("HH:mm:ss")
                .toFormatter();

        System.out.println("time_1 " + LocalTime.parse(time_1, formatter1));
        System.out.println("time_2 " + LocalTime.parse(time_2, formatter1));
        System.out.println("time_2 " + formatter1.format(LocalTime.parse(time_2, formatter1)));
        System.out.println("time_2 " + formatter2.format(LocalTime.parse(time_2, formatter1)));
    }
}

输出:

time_1 19:05:40
time_2 19:05
time_2 07:05:00pm
time_2 19:05:00