1

I have my date and time stored in string i.e my string contains str ="18/01/2013 5:00:00 pm". How can I convert it to 24 format time in android?

Andro Selva
  • 53,910
  • 52
  • 193
  • 240
user1448108
  • 467
  • 2
  • 10
  • 28

5 Answers5

2

You can use two SimpleDateFormat instances: one to parse the input as a date and a second to format the date as a string with the desired format.

For example, formattedDate in the code below will be 18/01/2013 17:00:00:

String str = "18/01/2013 5:00:00 pm";
SimpleDateFormat input = new SimpleDateFormat("dd/MM/yyyy hh:mm:ss a");
Date dt = input.parse(str);

SimpleDateFormat output = new SimpleDateFormat("dd/MM/yyyy HH:mm:ss");
String formattedDate = output.format(dt); //contains 18/01/2013 17:00:00

Notes:

  • hh is for Hour in am/pm (1-12) whereas HH is for Hour in day (0-23).
  • for more formatting options, check the javadoc
assylias
  • 321,522
  • 82
  • 660
  • 783
1

try

    String str ="18/01/2013 5:00:00 pm";
    Date date = new SimpleDateFormat("dd/MM/yyyy hh:mm:ss a").parse(str);
    str = new SimpleDateFormat("dd/MM/yyyy HH:mm:ss").format(date);
    System.out.println(str);

output

18/01/2013 17:00:00
Evgeniy Dorofeev
  • 133,369
  • 30
  • 199
  • 275
1

To get AM PM and 12 hour date format use hh:mm:ss a as string formatter WHERE hh is for 12 hour format and a is for AM PM format.

Note: HH is for 24 hour and hh is for 12 hour date format

SimpleDateFormat formatter = new SimpleDateFormat("mm/dd/yyyy hh:mm:ss a");
            String newFormat = formatter.format(testDate);

Example

String date = "18/01/2013 5:00:00 pm";
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy/mm/dd HH:MM:SS");
        Date testDate = null;
        try {
            testDate = sdf.parse(date);
        }catch(Exception ex){
            ex.printStackTrace();
        }
        SimpleDateFormat formatter = new SimpleDateFormat("mm/dd/yyyy hh:mm:ss a");
        String newFormat = formatter.format(testDate);
        System.out.println(".....Date..."+newFormat);
GrIsHu
  • 29,068
  • 10
  • 64
  • 102
0

You can use SimpleDateFormat for that:

SimpleDateFormat dateFormat = new SimpleDateFormat(dd/mm/yyyy HH:mm:ss");

Refer to this which was opposite to your requirement. Just posted the link so you might get the idea of difference that HH and hh makes.

Community
  • 1
  • 1
MysticMagicϡ
  • 28,593
  • 16
  • 73
  • 124
0

Try using the java SimpleDateFormat class.

Example:

SimpleDateFormat df = new SimpleDateFormat("dd/MM/yyyy HH:mm:ss");
df.parse(date);

The upper case HH use a 24h format

Dhanesh Budhrani
  • 190
  • 3
  • 15