Java获取年月日(格式:xxxx年xx月xx日)的方法详解
一、使用 Java 8 中的 LocalDate 类:
在 Java 8 中,可以使用 LocalDate 类来获取当前的年、月、日,并进行格式化。
示例代码:
import java.time.LocalDate; import java.time.format.DateTimeFormatter; public class Main { public static void main(String[] args) { LocalDate currentDate = LocalDate.now(); DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy年MM月dd日"); String formattedDate = currentDate.format(formatter); System.out.println("当前日期:" + formattedDate); } }
在上述示例中,我们使用 LocalDate.now() 方法获取当前日期,并使用 DateTimeFormatter 类指定日期的格式模式为 “yyyy年MM月dd日”。然后,我们通过调用 format() 方法将日期格式化为字符串。
二、使用 SimpleDateFormat 类:
在旧版本的 Java 中,可以使用 SimpleDateFormat 类来获取当前的年、月、日,并进行格式化。
示例代码:
import java.text.SimpleDateFormat; import java.util.Date; public class Main { public static void main(String[] args) { Date currentDate = new Date(); SimpleDateFormat formatter = new SimpleDateFormat("yyyy年MM月dd日"); String formattedDate = formatter.format(currentDate); System.out.println("当前日期:" + formattedDate); } }
在上述示例中,我们使用 new Date() 获取当前日期,并使用 SimpleDateFormat 类指定日期的格式模式为 “yyyy年MM月dd日”。然后,我们通过调用 format() 方法将日期格式化为字符串。
总结
通过本文的介绍,你学习了如何获取当前的年、月、日,并将其格式化为 “xxxx年xx月xx日” 的形式。你了解了使用 Java 8 中的 LocalDate 类和旧版本中的 SimpleDateFormat 类来实现日期的获取和格式化。
根据你的开发环境和需求,选择适合的方法来获取年月日,并根据需要进行格式化和处理。
到此这篇关于Java获取年月日(格式:xxxx年xx月xx日)的方法详解的文章就介绍到这了,更多相关Java获取年月日内容请搜索脚本之家以前的文章或继续浏览下面的相关文章希望大家以后多多支持脚本之家!
相关文章
SpringBoot做junit测试的时候获取不到bean的解决
这篇文章主要介绍了SpringBoot做junit测试的时候获取不到bean的解决方案,具有很好的参考价值,希望对大家有所帮助。如有错误或未考虑完全的地方,望不吝赐教2021-09-09org.apache.zookeeper.KeeperException.BadVersionException异常的解
在使用Apache ZooKeeper进行分布式协调时,你可能会遇到org.apache.zookeeper.KeeperException.BadVersionException异常,本文就来介绍一下解决方法,感兴趣的可以了解一下2024-03-03Spring boot集成spring session实现session共享的方法
这篇文章主要介绍了Spring boot集成spring session实现session共享的方法,小编觉得挺不错的,现在分享给大家,也给大家做个参考。一起跟随小编过来看看吧2019-06-06
最新评论