-2

How can I convert 24 hours time format into 12 hours format? I know this question has been asked many times, but my problem is different. My current time is:

Tue Nov 07 18:44:47 GMT+05:00 2017

I just want 6:44 pm from my date time. I tried this:

private void convertTime(String time)
{
    try {
        final SimpleDateFormat sdf = new SimpleDateFormat("H:mm");
        final Date dateObj = sdf.parse(time);
        System.out.println(dateObj);
        System.out.println(new SimpleDateFormat("K:mm a").format(dateObj));
    } catch (final ParseException e) {
        e.printStackTrace();
    }
}
Phantômaxx
  • 37,901
  • 21
  • 84
  • 115
Innocent
  • 703
  • 10
  • 21
  • How is your problem different? In what way does your attempt fail? Please quote any error messages and any stacktrace verbatim. – Ole V.V. Nov 19 '17 at 17:56
  • @Ole When I was posting this question I was not aware about my problem and I think that it is different from the problem that i asked earlier but after getting suitable answer i got to know that this is not different than the questions which have been asked earlier – Innocent Jul 13 '18 at 13:12

3 Answers3

3
final SimpleDateFormat sdf = new SimpleDateFormat("hh:mm");

Using hh will give you 12 hours format and HH 24 hour format. More details on documentation.

Edit:

Your initial format must be the following in order to parse your date string to a Date object:

final SimpleDateFormat sdf = new SimpleDateFormat("EEE MMM d HH:mm:ss 'GMT'Z yyyy");
final Date dateObj = sdf.parse(time);

After that you can format time to your needs.

Cătălin Florescu
  • 5,012
  • 1
  • 25
  • 36
  • but i have this time Tue Nov 07 18:44:47 GMT+05:00 2017 and i need only hours and minutes with 12 hours format – Innocent Nov 07 '17 at 08:37
2

From SimpleDateFormat documentation:

"h:mm a": 12:08 PM

So the format you need for:

I just want 6:44 pm from my date time

is:

final SimpleDateFormat sdf1 = new SimpleDateFormat("EEE MMM d HH:mm:ss z yyyy");
Date date = sdf1.parse(time);
final SimpleDateFormat sdf = new SimpleDateFormat("h:mm a");
String newDateString = sdf.format(date);
pleft
  • 7,567
  • 2
  • 21
  • 45
  • but i have this time in string "Tue Nov 07 18:44:47 GMT+05:00 2017" and I need only hours and minutes with 12 hours format – Innocent Nov 07 '17 at 08:40
  • Ok updated my answer, `time` is the `String time` parameter of your `convertTime` method – pleft Nov 07 '17 at 08:48
1
try {
    final SimpleDateFormat sdf = new SimpleDateFormat("hh:mm");
    final Date dateObj = sdf.parse(time);
    System.out.println(dateObj);
    System.out.println(new SimpleDateFormat("K:mm a").format(dateObj));
} catch (final ParseException e) {
    e.printStackTrace();
}
mrid
  • 5,782
  • 5
  • 28
  • 71