Java 无法从日期格式中仅获取日期日期?
如何从日期格式中获取日期 年月日 例如: 2015年5月4日 我只需要日期为Java 无法从日期格式中仅获取日期日期?,java,date,date-format,Java,Date,Date Format,如何从日期格式中获取日期 年月日 例如: 2015年5月4日 我只需要日期为04 下面是代码片段: DateFormat dateFormat = new SimpleDateFormat("dd/MM/yyyy"); Date date = new Date(); Calendar cal = Calendar.getInstance(); cal.add(Calendar.DAY_OF_MONTH,1); System.out.println(dateFormat.format(date)
04
下面是代码片段:
DateFormat dateFormat = new SimpleDateFormat("dd/MM/yyyy");
Date date = new Date();
Calendar cal = Calendar.getInstance();
cal.add(Calendar.DAY_OF_MONTH,1);
System.out.println(dateFormat.format(date));
如何解决此问题?使用
cal.get(日历.日期/月份)
只需更改DateFormat DateFormat=new SimpleDateFormat(“dd/MM/yyyy”)
toDateFormat DateFormat=newsimpledateformat(“dd”)代码>
或者使用cal.get(日历日/月)代码>您需要更改显示所需数据格式的模式:
DateFormat DateFormat=新的SimpleDateFormat(“dd”)
而不是
DateFormat DateFormat=新的简化格式(“dd/MM/yyyy”)
更新:
Java1.8更新了数据和时间API
下面是我检查过的代码片段:
LocalDate lastAprilDay = LocalDate.of(2014, Month.APRIL, 30);
System.out.println("last april day: " + lastAprilDay);
LocalDate firstMay = lastAprilDay.plusDays(1);
System.out.println("should be first may day: " + firstMay);
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("dd");
String formatDate = formatter.format(firstMay);
System.out.println("formatted date: " + formatDate);
输出:
有关更多信息,请参阅此类的Java文档:
我也试过。。在另一种情况下,我必须增加日期,但它不能正常工作(例如:如果我增加一天,则4月有30天,当前日期显示为31天,而不是5月1日),请建议如何超过此限制???@ShivaRavi您使用了哪个版本的JDK?@ShivaRavi进行日期操作,您必须使用Calendar类,不是日期类。@nazar_art我使用的是jdk-8u40-windows-x64@nazar_art:非常感谢。。我会试试这个让你知道:)看看下面的问题:@ShivaRavi你的问题解决了吗?
last april day: 2014-04-30
should be first may day: 2014-05-01
formatted date: 01