我的日期格式为MM/DD/YYYY,时间格式为HHMM(24 小时时间,不带冒号)。这两个字符串都在一个数组中。我想将其存储为一个字符串 - 也许类似于 "MM-DD-YYYY HH:MM" - 然后能够将其转换为书面日期,例如 "January 1, 2014 16:15" 当我向用户展示它时。我怎样才能做到这一点?
这是我的代码:
String date = "05/27/2014 23:01";
Date df = new SimpleDateFormat("MM/DD/YYYY HH:mm").parse(date);
System.out.println(df);
然而,这就是我得到的:“Sun Dec 29 23:01:00 EST 2013”
我正在寻找的输出是:“2013 年 12 月 29 日 23:01”
最佳答案
SimpleDateFormat
是正确的选择;以所需的有意义的日期和时间格式解析字符串,最后将日期打印为所需的字符串。
您指定 2 种格式如下:
SimpleDateFormat dateFormat = new SimpleDateFormat("MM/dd/yyyy");
SimpleDateFormat timeFormat = new SimpleDateFormat("HHmm");
考虑一个简单的硬编码日期和时间数组(不是最好的显示方式,但你的问题将其称为数组):
String[] array = { "12/31/2013", "1230" };
您必须在日历实例中设置这些解析的日期:
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();
}
}
输出:
December 31, 2013 at 12:30
关于java - 在Java中为24小时时间添加冒号?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20862558/