tl;dr
As stated in correct Answer by Don Brody, your formatting pattern was incorrect, using HH
(for 24-hour clock) where it should have been lowercase hh
(for 12-hour clock). You likely also have a problem with your JVM’s current default time zone not being set to what you expect.
Also… Your problem is moot. You are using terrible old classes that were supplanted years ago by java.time.
LocalTime // Represent time-of-day without date and without time zone.
.now() // Capture the current time-of-day as seen in the JVM’s current default time zone. Better to pass the optional `ZoneId` argument to specify explicitly the desired/expected time zone.
.format( // Generate a `String` representing our time-of-day value.
DateTimeFormatter
.ofLocalizedTime( FormatStyle.SHORT ) // Automatically localize rather than hard-code a specific formatting pattern.
.withLocale( Locale.US ) // Locale determines the human language and cultural norms used in localizing.
) // Returns a `String` object.
10:09 PM
Use java.time
You are using terrible old classes now supplanted by the java.time classes.
Get the current time-of-day.
LocalTime lt = LocalTime.now() ; // Capture the current time-of-day using the JVM’s current default time zone.
Better to explicitly state the desired/expected time zone than rely implicitly on the JVM’s current default time zone.
ZoneId z = ZoneId.of( "America/Montreal" ) ;
LocalTime lt = LocalTime.now( z ) ;
Generate a string in AM-PM format.
DateTimeFormatter f = DateTimeFormatter.ofPattern( "hh:mm a" ) ; // Lowercase `hh` for 12-hour clock, uppercase `HH` for 24-hour clock.
String output = lt.format( f ) ;
Even better, let java.time automatically localize for you.
Locale locale = Locale.US ;
DateTimeFormatter f2 = DateTimeFormatter.ofLocalizedTime( FormatStyle.SHORT ).withLocale( locale ) ;
String output2 = lt.format( f2 ) ;
See that code run live at IdeOne.com.
lt.toString(): 22:09:19.825
output: 10:09 PM
output2: 10:09 PM
About java.time
The java.time framework is built into Java 8 and later. These classes supplant the troublesome old legacy date-time classes such as java.util.Date
, Calendar
, & SimpleDateFormat
.
The Joda-Time project, now in maintenance mode, advises migration to the java.time classes.
To learn more, see the Oracle Tutorial. And search Stack Overflow for many examples and explanations. Specification is JSR 310.
You may exchange java.time objects directly with your database. Use a JDBC driver compliant with JDBC 4.2 or later. No need for strings, no need for java.sql.*
classes.
Where to obtain the java.time classes?