我在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());
}
Run Code Online (Sandbox Code Playgroud)
使用SimpleDateFormat.
SimpleDateFormat input = new SimpleDateFormat("ddMMyyyy");
SimpleDateFormat output = new SimpleDateFormat("dd/MM/yyyy");
System.out.println(output.format(input.parse("02122012"))); // 02/12/2012
Run Code Online (Sandbox Code Playgroud)
正如乔恩斯基特建议,您还可以设置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
Run Code Online (Sandbox Code Playgroud)