DateTimeFormatter 的操作与使用 -- 通俗易懂
在上一章我们讲解了LocalDate、LocalTime、LocalDateTime、Instant的操作与使用,下面讲解它们之间是如何进行格式化
DateTimeFormatter这个类它只提供了时间格式化的类型,就是按你指定的格式,或者按jdk默认的格式,需要进行调用的则是时间类本身来进行调用才能进行格式化
LocalDate、LocalTime 的api是有2个方法,分别是:parse()、format()方法,时间类型的转换可以调用这2个来进行日期时间类型的转换
E parse(CharSequence text)
E parse(CharSequence text, DateTimeFormatter formatter)
String format(DateTimeFormatter formatter)
1.字符串转换成日期时间类型
private static void testStringT0LocalDate() { // String --> LocalDate LocalDate localDate = LocalDate.parse("2019-12-07");
DateTimeFormatter pattern = DateTimeFormatter.ofPattern("yyyy年MM月dd日");
System.out.println(LocalDate.parse("2019-10-09").format(pattern));
// String --> LocalTime LocalTime localTime = LocalTime.parse("07:43:53"); // String -->LocalDateTime DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd hh:mm:ss"); // 12小时 DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss"); // 24小时
LocalDate localDate = LocalDate.parse("2019-12-07 07:43:53",formatter); System.out.println(localDate); System.out.println(localTime); System.out.println(localDate); }
2.日期时间类型转换成字符串
private static void testLocalDateToString() { //localDate --> String LocalDate localDate = LocalDate.now(); String format1 = localDate.format(DateTimeFormatter.BASIC_ISO_DATE); //yyyyMMdd String format2 = localDate.format(DateTimeFormatter.ISO_DATE); //yyyy-MM-dd //2.LocalTime --> String LocalTime localTime = LocalTime.now(); String format3 = localTime.format(DateTimeFormatter.ISO_TIME); //20:19:22.42 DateTimeFormatter formatter = DateTimeFormatter.ofPattern("hh:mm:ss"); String format4 = localTime.format(formatter); //3.LocalDateTime --> String LocalDateTime localDateTime = LocalDateTime.now(); DateTimeFormatter formatter2 = DateTimeFormatter.ofPattern("yyyy-MM-dd hh:mm:ss"); String format5 = localDateTime.format(formatter2); System.out.println(format1); System.out.println(format2); System.out.println(format3); System.out.println(format4); System.out.println(format5); }
由于本人是自己学习总结出来的,有不足之处,请各位看官批评指出,我将及时改正,以提高知识总结的正确性和严谨性,为大家学习提供方便!!!
如若转载,请注明出处!!!
标签:
jdk1.8的操作与使用
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 基于Microsoft.Extensions.AI核心库实现RAG应用
· Linux系列:如何用heaptrack跟踪.NET程序的非托管内存泄露
· 开发者必知的日志记录最佳实践
· SQL Server 2025 AI相关能力初探
· Linux系列:如何用 C#调用 C方法造成内存泄露
· Manus爆火,是硬核还是营销?
· 终于写完轮子一部分:tcp代理 了,记录一下
· 震惊!C++程序真的从main开始吗?99%的程序员都答错了
· 别再用vector<bool>了!Google高级工程师:这可能是STL最大的设计失误
· 单元测试从入门到精通