【发布时间】:2014-06-12 12:34:22
【问题描述】:
我在 google 上搜索过,但找不到如何获取字符串:xx:xx AM/PM(例如下午 3:30)并将其更改为现在为 24小时。
例如,上一个时间是“15:30”。我研究过简单地使用 if then 语句来操作字符串,但这似乎很乏味。有什么简单的方法可以做到这一点?
Input: 3:30 PM
Expected Output: 15:30
【问题讨论】:
我在 google 上搜索过,但找不到如何获取字符串:xx:xx AM/PM(例如下午 3:30)并将其更改为现在为 24小时。
例如,上一个时间是“15:30”。我研究过简单地使用 if then 语句来操作字符串,但这似乎很乏味。有什么简单的方法可以做到这一点?
Input: 3:30 PM
Expected Output: 15:30
【问题讨论】:
试试
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
【讨论】:
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/
【讨论】:
aa是什么意思?
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))
;
工作正常,结果与您想要的一样。
【讨论】:
这是要走的路:
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
【讨论】:
在我添加语言环境之前,我的没有工作 像这样:
SimpleDateFormat date12Format = new SimpleDateFormat("hh:mm aa", Locale.US);
【讨论】:
您可以轻松地使用此方法将 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;
}
}
【讨论】: