Java更简洁的方法,输出当前时间(hh:mm)

LocalDateTime now = LocalDateTime.now();
int hour = now.getHour();
int min = now.getMinute();
String currentTime = hour < 10 ? "0" : "" + hour + ":" + min;

System.out.println(currentTime);

需要判断,hour是一位还是2位,否则补0

更简洁的方式,利用string format的%02d,可以自动补0
LocalDateTime now = LocalDateTime.now();
String currentTime = String.format("%02d:%02d", now.getHour(), now.getMinute());
System.out.println(currentTime);
posted @ 2024-05-31 10:23  daibiao123  阅读(117)  评论(0)    收藏  举报