java.time
You need to decide on a time zone for that. Once you know your time zone, we can define a couple of constants, for example:
private static final ZoneId ZONE = ZoneId.of("America/Antigua");
private static final DateTimeFormatter TIME_PARSER
= DateTimeFormatter.ofPattern("h:mma", Locale.ENGLISH);
I am using java.time, the modern Java date and time API. Substitute your time zone instead of America/Antigua
. If you want the default time zone of your device, set ZONE
to ZoneId.systemDefault()
.
Now we can do:
String userTimeString = "8:30AM";
OffsetDateTime timestamp = ZonedDateTime.of(
LocalDate.now(ZONE),
LocalTime.parse(userTimeString, TIME_PARSER),
ZONE)
.toOffsetDateTime();
System.out.println(timestamp);
Output when I ran today:
2021-08-30T08:30-04:00
Did you want to save the timestamp in your SQL database? Since JDBC 4.2 you can save an OffsetDateTime
into an SQL column of data type timestamp with time zone
. See the links.
Links