如何使用LocalDate实现不同日期格式之间的转换?
如何将一种日期格式转换为另一种日期格式?
可以利用Java 8+提供的LocalDate和DateTimeFormatter类实现日期格式转换,以下是具体实现代码及测试用例:
核心实现代码
public class DateUtil { public static LocalDate localDateToAnotherLocalDate(String oldPattern, String newPattern, String input) { DateTimeFormatter oldFormat = DateTimeFormatter.ofPattern(oldPattern); DateTimeFormatter newFormat = DateTimeFormatter.ofPattern(newPattern); LocalDate localDate = LocalDate.parse(input, oldFormat); String output = localDate.format(newFormat); return getLocalDate(output, newPattern); } public static LocalDate getLocalDate(String date, String datePattern) { DateTimeFormatter formatter = DateTimeFormatter.ofPattern(datePattern); return LocalDate.parse(date, formatter); } }
测试用例
import org.junit.jupiter.api.Test; import static org.junit.jupiter.api.Assertions.assertEquals; public class DateUtilTest { @Test void getLocalDateToAnotherLocalDateTest() { LocalDate localDate = DateUtil.localDateToAnotherLocalDate("yyyy-MM-dd", "dd-MM-yyyy", "2022-11-20"); System.out.println("转换后的LocalDate: " + localDate.toString()); assertEquals("20-11-2022", localDate.toString()); } }
补充说明
LocalDate仅表示日期(不含时间),本身不存储格式信息,其toString()方法的输出格式由类自身定义。如果需求是获取特定格式的字符串,直接返回localDate.format(newFormat)即可,无需再转换回LocalDate。DateTimeFormatter用于定义日期的解析和格式化规则,支持各种自定义格式(如yyyy-MM-dd、dd/MM/yyyy等)。
内容的提问来源于stack exchange,提问作者bharathi
相关产品推荐
相关产品推荐

