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

8

我在谷歌上搜索了一下,但并没有找到如何将字符串xx:xx AM/PM(例如3:30 PM)转换为24小时格式的方法。

举个例子,上面提到的时间应该是"15:30"。我尝试使用if-then语句来操作字符串,但似乎非常繁琐。有没有更简单的方法呢?

Input: 3:30 PM
Expected Output:  15:30
6个回答

25

尝试

  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
非常欢迎。如需更多信息,请查看SimpleDateFormat - Braj
有些手机会奇怪地显示“解析异常”,如果你遇到这个错误,请使用新的SimpleDateFormat("hh:mm aa")。 - Bala Vishnu

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
这是一个链接,指向 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

1

看起来我晚了几秒钟 :( - Matej Špilár
aa 的意思是什么? - Braj
我在SimpleDateFormat上没有找到任何相关内容。 - Braj
这里没有...http://javatechniques.com/blog/dateformat-and-simpledateformat-examples/还有http://stackoverflow.com/questions/5893297/whats-the-difference-in-using-a-and-aaa-in-simpledateformat - Matej Špilár

1
我的代码没有工作,直到我添加了Locale,就像这样:

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

0

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

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

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接