java.time.LocalTime
You are using the wrong class. Date
represents a moment, a date with time-of-day in UTC. And that terrible class is now legacy, supplanted years ago by the modern java.time classes.
The LocalTime
class represents a time-of-day without a date and without a time zone or offset-from-UTC.
String input = "15:30:18" ;
LocalTime lt = LocalTime.parse( input ) ;
ISO 8601
Create a string in standard ISO 8601 format.
String output1 = lt.toString() ;
15:30:18
Localize
Create a string in localized format.
DateTimeFormatter f = DateTimeFormatter.ofLocalizedTime( FormatStyle.MEDIUM ).withLocale( Locale.US ) ;
String output2 = lt.format( f ) ;
3:30:18 PM
Localize to Québec, just for fun.
DateTimeFormatter fQuébec = DateTimeFormatter.ofLocalizedTime( FormatStyle.MEDIUM ).withLocale( Locale.CANADA_FRENCH ) ;
String output3 = lt.format( fQuébec ) ;
15 h 30 min 18 s
See all this code run live at IdeOne.com.
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.
Where to obtain the java.time classes?