Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Time formatting using SimpleDateFormat in java

My requirement is to display date on webpage in hh:mm format. But, it should not display zero before the hour value if it is a 1-digit number.

For example - It should be displayed as : 11:30 AM, 9:15 AM, 1:00 PM.

I tried to resolve this but the only issue coming here is in removing the extra 0 from the 1-digit hour value.

Input time is in format - hh:mm:ss .

The date value is a string initially. It is parsed as date in below format first of all-

final SimpleDateFormat dfParse = new SimpleDateFormat("HH:mm:ss");
startTimeFmt = dfParse.parse(startTime);

Then it is formatted in below format -

final SimpleDateFormat dfFormat = new SimpleDateFormat("hh:mm a");
startTime = dfFormat.format(startTimeFmt);
like image 979
BullsEye Avatar asked Feb 12 '23 15:02

BullsEye


1 Answers

Try this:

Date date = new SimpleDateFormat("hh:mm:ss").parse("07:15:45");
String newDate = new SimpleDateFormat("h:mm a").format(date);

This will print 7:15 AM

like image 159
Jonas Avatar answered Feb 27 '23 10:02

Jonas