我环顾四周,找不到符合我需要的东西。
我得到以下字符串:
"March 13, 2013"
并需要将其转换为
"2013-03-13"
我尝试使用此代码:
SimpleDateFormat inputFormat = new SimpleDateFormat("MMMMMMMMMM dd, YYYY");
SimpleDateFormat outputFormat = new SimpleDateFormat("YYYY-MM-dd");
Date d = inputFormat.parse(startDate);
System.out.println(outputFormat.format(d));
但我得到“203-12-30”..为什么会这样?
答案 0 :(得分:3)
Y
代表周年。尝试使用y
SimpleDateFormat outputFormat = new SimpleDateFormat("yyyy-MM-dd");
答案 1 :(得分:1)
我只是复制并粘贴了你的代码,做了一些小改动,得到了你想要的结果。我做的主要改变是将inputFormat中的大写“Y”改为小写“y”的outputFormat。无论如何,你是:
String startDate = "March 13, 2013";
SimpleDateFormat inputFormat = new SimpleDateFormat("MMMMMMMMMM dd, yyyy");
SimpleDateFormat outputFormat = new SimpleDateFormat("yyyy-MM-dd");
try {
Date d = inputFormat.parse(startDate);
System.out.println(outputFormat.format(d));
} catch (ParseException e) {
e.printStackTrace();
}
答案 2 :(得分:0)
尝试使用以下代码:
String startDate = "March 13, 2013";
SimpleDateFormat inputFormat = new SimpleDateFormat("MMMM dd, yyyy",Locale.ENGLISH);
SimpleDateFormat outputFormat = new SimpleDateFormat("yyyy-MM-dd");
Date d = inputFormat.parse(startDate);
System.out.println(outputFormat.format(d));