如何将localdatetime转换为格式“ dd/mm/yyyy”



我在将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;
    }
}

它返回日期,但是以 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);
}

日期和SimpleDateFormat是"旧"一代的,并且在一段时间内仍将大量使用。但是应该尝试最大程度地减少其用法。

format()执行的日期格式返回带有预期格式的字符串,但是当您使用parse()解析时,您会丢失该格式,因为Date并非旨在持有特定格式,结果是什么输出时,您会看到日期是toString()Date对象的表示。

最新更新