Converting XX:XX AM/PM to 24 Hour Clock

前端 未结 6 1711
抹茶落季
抹茶落季 2021-02-15 16:41

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 e

6条回答
  •  别跟我提以往
    2021-02-15 16:58

    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

提交回复
热议问题