Bar*_*ers 70
试试这个:
import java.text.SimpleDateFormat;
import java.util.Date;
public class Main {
public static void main(String [] args) throws Exception {
SimpleDateFormat displayFormat = new SimpleDateFormat("HH:mm");
SimpleDateFormat parseFormat = new SimpleDateFormat("hh:mm a");
Date date = parseFormat.parse("10:30 PM");
System.out.println(parseFormat.format(date) + " = " + displayFormat.format(date));
}
}
Run Code Online (Sandbox Code Playgroud)
产生:
10:30 PM = 22:30
Run Code Online (Sandbox Code Playgroud)
请参阅:http://download.oracle.com/javase/1.5.0/docs/api/java/text/SimpleDateFormat.html
Clo*_*oud 16
在Java 8及更高版本中,可以使用类java.time.LocalTime在一行中完成它.
在格式化模式中,小写hh表示12小时制,而大写HH表示24小时制.
代码示例:
String result = // Text representing the value of our date-time object.
LocalTime.parse( // Class representing a time-of-day value without a date and without a time zone.
"03:30 PM" , // Your `String` input text.
DateTimeFormatter.ofPattern( // Define a formatting pattern to match your input text.
"hh:mm a" ,
Locale.US // `Locale` determines the human language and cultural norms used in localization. Needed here to translate the `AM` & `PM` value.
) // Returns a `DateTimeFormatter` object.
) // Return a `LocalTime` object.
.format( DateTimeFormatter.ofPattern("HH:mm") ) // Generate text in a specific format. Returns a `String` object.
;
Run Code Online (Sandbox Code Playgroud)
请参阅IdeOne.com上的此代码.
15:30
请参阅Oracle教程.
12 到 24 小时时间转换,如果更改输出和输入 SimpleDateFormat 类参数中的时间格式,则可以反转
测试数据输入:
字符串输入=“07:05:45PM”;timeCoversion12to24(输入);
输出
19:05:45
public static String timeCoversion12to24(String twelveHoursTime) throws ParseException {
//Date/time pattern of input date (12 Hours format - hh used for 12 hours)
DateFormat df = new SimpleDateFormat("hh:mm:ssaa");
//Date/time pattern of desired output date (24 Hours format HH - Used for 24 hours)
DateFormat outputformat = new SimpleDateFormat("HH:mm:ss");
Date date = null;
String output = null;
//Returns Date object
date = df.parse(twelveHoursTime);
//old date format to new date format
output = outputformat.format(date);
System.out.println(output);
return output;
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
86152 次 |
| 最近记录: |