Search code examples
javaandroidandroid-date

How can I reformat date and time?


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();
    }
}

Solution

  • 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);