Converting XX:XX AM/PM to 24 Hour Clock

Try

  String time = "3:30 PM";

    SimpleDateFormat date12Format = new SimpleDateFormat("hh:mm a");

    SimpleDateFormat date24Format = new SimpleDateFormat("HH:mm");

    System.out.println(date24Format.format(date12Format.parse(time)));

output:

15:30

try this: 

String string = "3:35 PM";
    Calendar calender = Calendar.getInstance();
    DateFormat format = new SimpleDateFormat( "hh:mm aa");
    Date date;
    date = format.parse( string );
    calender.setTime(date);

    System.out.println("Hour: " + calender.get(Calendar.HOUR_OF_DAY));
    System.out.println("Minutes: " + calender.get(Calendar.MINUTE))

;

works fine and same result as what you would like.


Here is a link to the SimpleDateFormat Javadoc

This is the way to go :

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;


public class TimeParsing {

    public static void main(String[] args) {
        try {
            // Declare a date format for parsing
            SimpleDateFormat dateParser = new SimpleDateFormat("h:mm a");

            // Parse the time string
            Date date = dateParser.parse("3:30 PM");

            // Declare a date format for printing
            SimpleDateFormat dateFormater = new SimpleDateFormat("HH:mm");

            // Print the previously parsed time
            System.out.println(dateFormater.format(date));

        } catch (ParseException e) {
            System.err.println("Cannot parse this time string !");
        }
    }
}

Console output is : 15:30

Tags:

Time

Java

String