我正在使用 SimpleDateFormat 以这种格式“HH:MM a”获取同一函数中 2 个日期的小时和秒。两者的输出打印相同,并且大部分是第一次约会。它的代码如下:
//to get the time
public static void getHourAndTime(Date startDate, Date endDate){
SimpleDateFormat formatter = new SimpleDateFormat("HH:MM a");
String formattedstartTime = formatter.format(startDate);
System.out.println("startTime"+formattedstartTime);
String formattedEndTime = formatter.format(endDate);
System.out.println("endTime"+formattedEndTime);
}
任何解决方案/原因都会有所帮助。
编辑:这是应用程序中的一段旧代码,我试图更改它。
谢谢
Date
及其方法已过时且存在错误。除非您必须使用 Date,否则我会使用 java.time 包中的类。以下是通过修改您的代码所做的更改。
getHourAndTime(LocalDateTime.now(), LocalDateTime.now().plusSeconds(600));
public static void getHourAndTime(LocalDateTime startDate, LocalDateTime endDate) {
DateTimeFormatter dtf = DateTimeFormatter.ofPattern("HH:mm a");
System.out.println("startTime: " + startDate.format(dtf));
System.out.println("endTime: " + endDate.format(dtf));
}
版画
startTime: 11:53 AM
endTime: 12:03 PM