将 a 转换localDateTime为格式时遇到一些问题dd/MM/yyyy
这是我正在使用的方法:
public static Date localDateTimeToDateWithSlash(LocalDateTime localDateTime) {
if(localDateTime == null)
return null;
DateFormat format = new SimpleDateFormat("dd/MM/yyyy");
try {
return format.parse(localDateTime.format(slashDateFormater));
}
catch (Exception e) {
return null;
}
}
Run Code Online (Sandbox Code Playgroud)
它返回一个日期,但格式为2017-12-01T01:00但我需要它的格式dd/MM/yyyy。
日期不包含特定格式;有默认(可排序)ISO 格式,如 2017-12-19T12:55,由toString(). 在这种情况下,返回一个带有正确格式日期的字符串。
public static String localDateTimeToDateWithSlash(LocalDateTime localDateTime) {
return DateTimeFormatter.ofPattern("dd/MM/yyyy").format(localDateTime);
}
Run Code Online (Sandbox Code Playgroud)
Date 和 SimpleDateFormat 属于“老”代,在一段时间内仍会大量使用。但是应该尽量减少它们的使用。