如何在不导致字符串的情况下将LocalDate格式更改为LocalDate [英] How to change LocalDate format resulting into a LocalDate without resulting into a String

查看:129
本文介绍了如何在不导致字符串的情况下将LocalDate格式更改为LocalDate的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

需要将 dd-MM-yyyy 格式的Java LocalDate 转换为 dd/MM的 LocalDate /yyyy .

In a need to convert Java LocalDate of the format of dd-MM-yyyy into a LocalDate of dd/MM/yyyy.

尝试:

DateTimeFormatter dateFormat = DateTimeFormatter.ofPattern("dd/MM/yyyy");
LocalDate date = // LocalDate value in dd-MM-yyyy format
String stringDate = dateFormat.format(date);
LocalDate convertedDate = LocalDate.parse(stringDate, dateFormat);

但是仍然会导致以 dd-MM-yyyy 格式返回日期.有什么有效的方法吗?

But still it resulting into return a date in dd-MM-yyyy format. Any efficient way to do this?

推荐答案

LocalDate.java中的默认toString实现似乎以'-'作为分隔符进行了硬接线.因此,所有默认的打印语句将产生相同的格式.似乎唯一的出路是使用格式化程序并获取字符串输出.

The default toString implementation in LocalDate.java seems to be hardwired with '-' as a separator. So all default print statements will result into same format. Seems only way out would be to use a formatter and get a string output.

return buf.append(monthValue < 10 ? "-0" : "-")
            .append(monthValue)
            .append(dayValue < 10 ? "-0" : "-")
            .append(dayValue)
            .toString();

此外,LocalDate.parse(..)的目的不是转换日期格式.实际上,它的目的只是在String中获取日期值,并提供一个结果LocalDate实例.

Also, purpose of LocalDate.parse(..) is not to convert the date format. It's actually meant to just get a date value in String and give a resulting LocalDate instance.

希望这会有所帮助.

这篇关于如何在不导致字符串的情况下将LocalDate格式更改为LocalDate的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆