java年月日怎么获取(年月日.获取.java...)
如何获取 java 中的年月日?通过 date 类直接获取,year = date.getyear() + 1900。使用 java.time.localdate 类,year = date.getyear()。利用 calendar 类,year = calendar.get(calendar.year)。
如何获取 Java 中的年月日
直接获取
- Date 类:
Date date = new Date(); int year = date.getYear() + 1900; int month = date.getMonth() + 1; int day = date.getDate();
- java.time.LocalDate 类:
LocalDate date = LocalDate.now(); int year = date.getYear(); int month = date.getMonthValue(); int day = date.getDayOfMonth();
使用 Calendar 类
Calendar calendar = Calendar.getInstance(); int year = calendar.get(Calendar.YEAR); int month = calendar.get(Calendar.MONTH) + 1; int day = calendar.get(Calendar.DAY_OF_MONTH);
格式化日期
可以通过 SimpleDateFormat 类将日期格式化为字符串。
SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd"); String formattedDate = formatter.format(date);
注意:
- Date 类已弃用,建议使用 java.time 包。
- 在 java.time 中,月份从 1 开始,而不是 0。
- 月份和日期可以使用两位数字格式化,例如 "01" 和 "02"。
以上就是java年月日怎么获取的详细内容,更多请关注知识资源分享宝库其它相关文章!