将XX:XX AM / PM转换为24小时制

时间:2014-04-26 20:21:44

标签: java string time

我搜索了谷歌,但我找不到你如何拍摄字符串: xx:xx AM / PM (例如下午3:30)并更改它以便它现在在24小时。

因此,例如前一次将是" 15:30"。我已经研究过使用if then语句来操作字符串,但这看起来非常繁琐。有没有简单的方法呢?

Input: 3:30 PM
Expected Output:  15:30

6 个答案:

答案 0 :(得分:17)

尝试

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

输出:

15:30

答案 1 :(得分:3)

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

效果很好,结果和你想要的一样。

答案 2 :(得分:2)

以下是SimpleDateFormat Javadoc

的链接

这是要走的路:

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 !");
        }
    }
}

控制台输出为:15:30

答案 3 :(得分:1)

SimpleDateFormat inFormat = new SimpleDateFormat("hh:mm aa");
SimpleDateFormat outFormat = new SimpleDateFormat("HH:mm");
String time24 = outFormat.format(inFormat.parse(yourTimeString));

您也可以在此处详细了解转换时间http://deepeshdarshan.wordpress.com/2012/08/17/how-to-change-time-from-12-hour-format-to-24-hour-format-in-java/

答案 4 :(得分:1)

在我添加Locale之前,我没有工作 像这样:

SimpleDateFormat date12Format = new SimpleDateFormat("hh:mm aa", Locale.US);

答案 5 :(得分:0)

您可以轻松地使用此方法将 AM/PM 时间转换为 24 小时格式。只需将 12Hour 格式时间传递给此方法。

public static String convert_AM_PM_TimeTo_24(String ampmtime){
    SimpleDateFormat sdf = new SimpleDateFormat("hh:mm a");
    Date testTime = null;
    try {
        testTime = sdf.parse(ampmtime);
        SimpleDateFormat formatter = new SimpleDateFormat("HH:mm:ss");
        String newFormat = formatter.format(testTime);
        return newFormat;
    }catch(Exception ex){
        ex.printStackTrace();
        return ampmtime;
    }
}
相关问题