我在Java中有一个String,它是一个日期,但格式如下:
02122012
我需要将其重新格式化为 02/12/2012 如何做到这一点。
使用以下代码我一直回到 java.text.SimpleDateFormat@d936eac0
以下是我的代码..
public static void main(String[] args) {
// Make a String that has a date in it, with MEDIUM date format
// and SHORT time format.
String dateString = "02152012";
SimpleDateFormat input = new SimpleDateFormat("ddMMyyyy");
SimpleDateFormat output = new SimpleDateFormat("dd/MM/yyyy");
try {
output.format(input.parse(dateString));
} catch (Exception e) {
}
System.out.println(output.toString());
}
答案 0 :(得分:9)
使用SimpleDateFormat。
SimpleDateFormat input = new SimpleDateFormat("ddMMyyyy");
SimpleDateFormat output = new SimpleDateFormat("dd/MM/yyyy");
System.out.println(output.format(input.parse("02122012"))); // 02/12/2012
根据Jon Skeet的建议,您还可以在TimeZone
上设置Locale
和SimpleDateFormat
SimpleDateFormat englishUtcDateFormat(String format) {
SimpleDateFormat sdf = new SimpleDateFormat(format, Locale.ENGLISH);
sdf.setTimeZone(TimeZone.getTimeZone("UTC"));
return sdf;
}
SimpleDateFormat input = englishUtcDateFormat("ddMMyyyy");
SimpleDateFormat output = englishUtcDateFormat("dd/MM/yyyy");
System.out.println(output.format(input.parse("02122012"))); // 02/12/2012
答案 1 :(得分:0)
这是您编辑的问题中代码的问题:
System.out.println(output.toString());
您正在打印SimpleDateFormat
,而非打印format
的结果。实际上,你忽略调用format
的结果:
output.format(input.parse(dateString));
只需将其更改为:
System.out.println(output.format(input.parse(dateString)));
或者更清楚:
Date parsedDate = input.parse(dateString);
String reformattedDate = output.format(parsedDate);
System.out.println(reformattedDate);