简体   繁体   中英

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

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

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

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

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

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.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM