我想将一种日期格式转换成另一种日期格式。例如,我有这个字符串“05-Apr-23”,我想将它转换成这个字符串“05/04/23”。我做了这个实现,但没有用。
String oldDate = "05-Apr-23";
SimpleDateFormat sdf = new SimpleDateFormat("dd-mmm-yy");
Date dt = null;
try {
dt = sdf.parse(oldDate);
} catch (ParseException e) {
throw new CustomInternalServerException(oldDate + "is not a valid date");
}
SimpleDateFormat sdf1 = new SimpleDateFormat("dd/mm/yy");
return sdf1.format(dt);
我得到异常 ParseException:UnparseableDate:“05-Apr-23”。任何反馈将不胜感激!谢谢!
你只犯了一个小错误你必须使用 MMM 而不是 mmm , m 用于分钟, M 用于月份。
改变如下
dd-mmm-yy to dd-MMM-yy
dd/mm/yy to dd/MM/yy
最后还有一个错误,你必须返回 sdf1 而不是 sdf。
不要使用被取代的日期类。
Date
, SimpleDateFormat
- 不! LocalDate
, DateTimeFormatter
- 是的!
并且格式化模式区分大小写。对于月份的缩写名称,请使用大写字母“MMM”。
Locale
用于确定本地化该月份名称的人类语言和文化规范。
String oldDate = "05-Apr-23";
DateTimeFormatter dfFrom = DateTimeFormatter.ofPattern("dd-MMM-yy").withLocale( Locale.US );
DateTimeFormatter dfTo = DateTimeFormatter.ofPattern("dd/MM/yy");
String newDate = dfTo.format(LocalDate.parse(oldDate, dfFrom));
System.out.println(newDate);