Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Converting XX:XX AM/PM to 24 Hour Clock

Tags:

java

string

time

I have searched google and I cannot find out how you can take a string: xx:xx AM/PM (ex. 3:30 PM) and change it so that it is now in 24 hours.

So for example the previous time would be "15:30". I have looked into simply using if then statements to manipulate the string, however it seems very tedious. Is there any easy way to do this?

Input: 3:30 PM
Expected Output:  15:30
like image 671
user3505931 Avatar asked Apr 26 '14 20:04

user3505931


2 Answers

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.

like image 42
Rod_Algonquin Avatar answered Sep 24 '22 17:09

Rod_Algonquin


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
like image 198
Braj Avatar answered Sep 21 '22 17:09

Braj