I am taking time input from user as a String
in Java
and then converting it to LocalDateTime
object and saving it in a text file.
Problem
hh:mm a
is the format in which i am taking input form user. If i enter 12:30 PM
, it is saved in text file with current date as 2019-03-20T12:30
without indication of AM
or PM
.
Consequently, when i read it from text file, i get the date-time information without AM
or PM
.
Question
Why is AM
or PM
not saved in the text file and how can i get it from LocalDateTime
instance?
Code
Following method takes input from user, converts the user input in to LocalDateTime
instance and returns it which is then saved to text file as a 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
function is used to verify that user input is in correct format
Following method saves the data to text file
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
method
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();
}
When you are using StringBuilder
you are calling LocalDateTime.toString()
when the String
segment is appended. As per LocalDateTime.toString()
method 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
You need to save LocalDateTime
with custom format to get 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());