androidandroid-date

how to get date from 12 hour format to 24 hour format in android


hello I have date like..

String date="09:00 AM"

But I need 09:00:00

So I use following.

 String date="09:00 AM"  
 SimpleDateFormat f1 = new SimpleDateFormat("hh:mm:ss");
 Date d1= f1.parse(date);

But it give me parse exception.

Please help me to find this.

Thanks in advance.


Solution

  • That's not the correct format for parsing that date, you need something like:

    "hh:mm a"
    

    Once you have a date object, you can then use a different format to output it. The following code segment shows how:

    import java.text.SimpleDateFormat;
    import java.util.Date;
    
    String date = "09:27 PM";
    
    SimpleDateFormat h_mm_a   = new SimpleDateFormat("h:mm a");
    SimpleDateFormat hh_mm_ss = new SimpleDateFormat("HH:mm:ss");
    
    try {
        Date d1 = h_mm_a.parse(date);
        System.out.println (hh_mm_ss.format(d1));
    } catch (Exception e) {
        e.printStackTrace();
    }
    

    This outputs:

    21:27:00
    

    as you would expect.