-1
String s = "12:18:00";
DateFormat f1 = new SimpleDateFormat("hh:mm:ss");
Date d = f1.parse(s);
DateFormat f2 = new SimpleDateFormat("h:mma");
f2.format(d).toLowerCase(); // "12:18am"

Tried the above however it returns 11:18pm?

Pentium10
  • 204,586
  • 122
  • 423
  • 502
ericlee
  • 2,703
  • 11
  • 43
  • 68

1 Answers1

5

Maybe you can do something like this:

final String time = "12:18:00";

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").format(dateObj));
} catch (final ParseException e) {
    e.printStackTrace();
}

Taken from here.

Community
  • 1
  • 1
npinti
  • 51,780
  • 5
  • 72
  • 96
  • wow did you even try that? i tried on my phone and it gives same result. 11:48 – ericlee Nov 10 '11 at 20:15
  • I've tested his code on 3 different phones and it works fine using various times. – dymmeh Nov 10 '11 at 20:42
  • 1
    Try reading this [link](http://developer.android.com/reference/java/text/SimpleDateFormat.html) which describes the date formats. you may be looking for "h" where he has "K" above since K = 0-12 where as h = 1-12. Replace "K:mm" with "h:mma" to get 12:18pm However, the code above is correct and should be marked as such. Your problem may lie with the initial simple date format initialization. You have "hh:mm:ss" which is not the format you are providing to be parsed. Use "H:mm" as above. – dymmeh Nov 10 '11 at 20:53
  • are you sure u tested on 3 different phone with the same exact code and time time being final String time = "12:18:00"; – ericlee Nov 10 '11 at 20:59