One of entities in my application has Time member (TIME column in mysql db). I'd like to be able to read that time value from jstl form (just like any other string), so Spring can inject it into that time member using setter (as for other members). Moreover, i'd like to be able to apply some filtering to it, so i can enter both 01:00 and 1:00, and transform it to 01:00.
What Time class should I use? LocalTime, java.sql.Time or any other?
How do I apply pattern to value read? Should I do it in controller, or can I do it inside setter or so?
I've come across multiple ways of reading time from jsp, but i can't seem to find solution for applying pattern.
CHAR
or VARCHAR
).DateTimeFormatter
.Demo:
import java.time.LocalTime;
import java.time.format.DateTimeFormatter;
import java.time.format.DateTimeFormatterBuilder;
import java.util.Locale;
public class Main {
public static void main(String[] args) {
// Test strings
String[] times = { "1:00", "01:00", "1:00 pm", "1:00 am", "01:00 am", "01:00 pm" };
// Define the formatter
DateTimeFormatter inputFormatter = new DateTimeFormatterBuilder()
.parseCaseInsensitive()
.appendPattern("[h:m a][H:m]")
.toFormatter(Locale.ENGLISH);
DateTimeFormatter outputFormatter = DateTimeFormatter.ofPattern("HH:mm");
for (String strTime : times) {
LocalTime lt = LocalTime.parse(strTime, inputFormatter);
// String to be saved to the database
String formattedTime = lt.format(outputFormatter);
System.out.println(formattedTime);
}
}
}
Output:
01:00
01:00
13:00
01:00
01:00
13:00
Notes:
[ ]
as shown above.HH:mm
(i.e. 24-hour) format.