我正在将用户输入的时间作为Java
中的String
,然后将其转换为LocalDateTime
对象并将其保存在文本文件中.
问题
hh:mm a
是我从用户那里获取输入的格式。如果我输入12:30 PM
,它将保存在文本文件中,当前日期为2019-03-20T12:30
,而不指示AM
或PM
。
因此,当我从文本文件中读取它时,我得到的日期时间信息没有 AM
或 PM
。
问题
为什么 AM
或 PM
没有保存在文本文件中?我如何从 LocalDateTime
实例获取它?
代码
以下方法接受用户输入,将用户输入转换为 LocalDateTime
实例并返回,然后将其作为 String
保存到文本文件
private static LocalDateTime getTimeInput(String question) {
System.out.print(question);
String userInput = scanner.nextLine();
userInput = AppointmentManager.validateTimeString(userInput, question);
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd h:m a");
String todaysDateString = LocalDate.now().toString();
userInput = todaysDateString + " " + userInput;
return LocalDateTime.parse(userInput, formatter);
}
validateTimeString
函数用于验证用户输入的格式是否正确
以下方法将数据保存到文本文件
private static final File file = new File("appointments_data.txt");
public static void saveAppointmentInfo(Appointment appointment, boolean appendToFile) {
try (FileWriter fw = new FileWriter(file, appendToFile);
BufferedWriter bfw = new BufferedWriter(fw)) {
String str = AppointmentDataManager.getAppointmentInfoAsString(appointment);
bfw.write(str);
bfw.newLine();
} catch (IOException ex) {
ex.printStackTrace();
}
}
getAppointmentInfoAsString
方法
private static String getAppointmentInfoAsString(Appointment appointment) {
StringBuilder sb = new StringBuilder();
sb.append(appointment.getPatientId())
.append(";")
.append(appointment.getStartTime())
.append(";")
.append(appointment.getEndTime())
.append(";")
.append(appointment.getDoctor().getName());
return sb.toString();
}
最佳答案
当您使用StringBuilder
时,您将在附加String
段时调用LocalDateTime.toString()
。根据 LocalDateTime.toString()
方法 javadoc:
The output will be one of the following ISO-8601 formats:
- uuuu-MM-dd'T'HH:mm
- uuuu-MM-dd'T'HH:mm:ss
- uuuu-MM-dd'T'HH:mm:ss.SSS
- uuuu-MM-dd'T'HH:mm:ss.SSSSSS
- uuuu-MM-dd'T'HH:mm:ss.SSSSSSSSS
您需要使用自定义格式保存LocalDateTime
才能获取AM/PM:
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd h:m a");
sb.append(appointment.getPatientId())
.append(";")
.append(appointment.getStartTime().format(formatter))
.append(";")
.append(appointment.getEndTime().format(formatter))
.append(";")
.append(appointment.getDoctor().getName());
关于java - 从 LocalDateTime 实例获取 AM/PM 信息,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55263190/