更新时间:2023-02-26 18:05:03
SimpleDateFormat
是要走的路;以所需的有意义的日期和时间格式解析您的字符串,最后将您的日期打印为所需的字符串.
SimpleDateFormat
is the way to go; to parse your Strings in the required meaningful date and time formats and finally print your date as a required String.
您按如下方式指定 2 种格式:
You specify the 2 formats as follows:
SimpleDateFormat dateFormat = new SimpleDateFormat("MM/dd/yyyy");
SimpleDateFormat timeFormat = new SimpleDateFormat("HHmm");
考虑一个简单的日期和时间硬编码数组(不是***的显示方式,但您的问题称之为数组):
Considering a simple hardcoded array of date and time (not the best way to show but your question calls it an array):
String[] array = { "12/31/2013", "1230" };
您必须在日历实例中设置这些解析日期:
You would have to set these parsed dates in a Calendar instance:
Calendar cal = Calendar.getInstance();
cal.setTime(date);
cal.add(Calendar.HOUR, time.getHours());
cal.add(Calendar.MINUTE, time.getMinutes());
最后使用相同的 SimpleDateFormat
SimpleDateFormat newFormat = new SimpleDateFormat("MMMM dd, yyyy 'at' hh:mm");
以下是完整的工作代码:
public class DateExample {
public static void main(String[] args) {
SimpleDateFormat dateFormat = new SimpleDateFormat("MM/dd/yyyy");
SimpleDateFormat timeFormat = new SimpleDateFormat("HHmm");
String[] array = { "12/31/2013", "1230" };
try {
Date date = dateFormat.parse(array[0]);
Date time = timeFormat.parse(array[1]);
Calendar cal = Calendar.getInstance();
cal.setTime(date);
cal.add(Calendar.HOUR, time.getHours());
cal.add(Calendar.MINUTE, time.getMinutes());
SimpleDateFormat newFormat = new SimpleDateFormat(
"MMMM dd, yyyy 'at' hh:mm");
String datePrint = newFormat.format(cal.getTime());
System.out.println(datePrint);
} catch (ParseException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
输出:
2013 年 12 月 31 日 12:30
December 31, 2013 at 12:30