Issue
How can I format the "2010-07-14 09:00:02"
date string to depict just "9:00"
?
Solution
Use href="https://docs.oracle.com/en/java/javase/17/docs/api/java.base/java/time/format/DateTimeFormatter.html" rel="nofollow noreferrer">DateTimeFormatter
to convert between a date string and a real LocalDateTime
object. with a LocalDateTime
as starting point, you can easily apply formatting based on various patterns as definied in the javadoc of the DateTimeFormatter
.
String originalString = "2010-07-14 09:00:02";
LocalDateTime dateTime = LocalDateTime.parse(originalString, DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss"));
String newString = DateTimeFormatter.ofPattern("H:mm").format(dateTime); // 9:00
In case you're not on Java 8 or newer yet, use SimpleDateFormat
to convert between a date string and a real Date
object. with a Date
as starting point, you can easily apply formatting based on various patterns as definied in the javadoc of the SimpleDateFormat
.
String originalString = "2010-07-14 09:00:02";
Date date = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").parse(originalString);
String newString = new SimpleDateFormat("H:mm").format(date); // 9:00
Answered By - BalusC
Answer Checked By - Clifford M. (JavaFixing Volunteer)