4

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);
Gene Bo
  • 11,284
  • 8
  • 90
  • 137
BullsEye
  • 65
  • 1
  • 8
  • Here are some examples: http://www.mkyong.com/java/java-date-and-calendar-examples/ Try to give it a shot yourself :) – Linora Nov 07 '14 at 18:38
  • you can use System.out.println(new SimpleDateFormat("h:mm a").format(new Date())); – Prasad Khode Nov 07 '14 at 18:43
  • possible duplicate of [Month without leading zeros in Android](http://stackoverflow.com/questions/8681666/month-without-leading-zeros-in-android) – Basil Bourque Nov 07 '14 at 20:17

3 Answers3

5

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

Jonas
  • 1,315
  • 1
  • 18
  • 31
2

Have you tried the h:mm a format?

From documentation (http://pages.cs.wisc.edu/~cs368-2/JavaTutorial/jdk1.2/api/java/text/SimpleDateFormat.html):

Examples Using the US Locale:

Format Pattern                         Result
--------------                         -------
"yyyy.MM.dd G 'at' hh:mm:ss z"    ->>  1996.07.10 AD at 15:08:56 PDT
"EEE, MMM d, ''yy"                ->>  Wed, July 10, '96
"h:mm a"                          ->>  12:08 PM
"hh 'o''clock' a, zzzz"           ->>  12 o'clock PM, Pacific Daylight Time
"K:mm a, z"                       ->>  0:00 PM, PST
"yyyyy.MMMMM.dd GGG hh:mm aaa"    ->>  1996.July.10 AD 12:08 PM

Cheers!

Jesse Ivy
  • 335
  • 1
  • 10
1

Try this

DateFormat formatter = new SimpleDateFormat("h:mm:ss a", Locale.US);
System.out.println(formatter.format(new Date()));
αƞjiβ
  • 3,056
  • 14
  • 58
  • 95