user1448108
user1448108

Reputation: 487

How to convert date and time stored in string to 24 format time in android?

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?

Upvotes: 1

Views: 3558

Answers (5)

GrIsHu
GrIsHu

Reputation: 23638

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

Upvotes: 1

Evgeniy Dorofeev
Evgeniy Dorofeev

Reputation: 136022

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

Upvotes: 1

Dhanesh Budhrani
Dhanesh Budhrani

Reputation: 190

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

Upvotes: 0

assylias
assylias

Reputation: 328608

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

Upvotes: 2

MysticMagicϡ
MysticMagicϡ

Reputation: 28823

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.

Upvotes: 0

Related Questions