tl;dr
Use modern java.time classes.
Rather than hard-code a format, automatically localize.
LocalTime
.now()
.format(
DateTimeFormatter.ofLocalizedTime( FormatStyle.SHORT )
)
See this code run live at IdeOne.com.
5:08 PM
Avoid legacy classes
Never use the terrible Date
and SimpleDateFormat
classes. These were years ago supplanted by the modern java.time classes defined in JSR 310.
java.time
You appear to want the current time as seen in a particular time zone. Time zone is crucial. For any given moment, the time-of-day (and the date) vary around the globe by time zone.
ZoneId z = ZoneId.systemDefault() ; // Or ZoneId.of( "America/Edmonton" )
LocalTime now = LocalTime.now( z ) ;
Let java.time automatically localize for you.
Locale locale = Locale.CANADA_FRENCH ; // Or Locale.US etc.
DateTimeFormatter f = DateTimeFormatter.ofLocalizedTime( FormatStyle.SHORT ).withLocale( locale ) ;
String output = now.format( f ) ;
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
.
To learn more, see the Oracle Tutorial. And search Stack Overflow for many examples and explanations. Specification is JSR 310.
The Joda-Time project, now in maintenance mode, advises migration to the java.time classes.
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. Hibernate 5 & JPA 2.2 support java.time.
Where to obtain the java.time classes?