How to extract day, month and year from Date using Java? [duplicate]

六眼飞鱼酱① 提交于 2021-01-16 04:30:43

问题


SimpleDateFormat formatter = new SimpleDateFormat("yyyy/MM/dd");
Date date = formatter.parse("2020/05/06"); 

I need to extract day, month and year from it i.e.

int day = 06;
int  month = 05;
int year = 2020;

but when I use

int day = date.getDay();
int month = date.getMonth();
int day = date.getYear(); 

its not working.


回答1:


Don't use Date as it is deprecated. Use LocalDate and DateTimeFormatter as follows.

LocalDate ld  = LocalDate.parse("2020/05/06", 
              DateTimeFormatter.ofPattern("yyyy/MM/dd"));
int year = ld.getYear();
int month = ld.getMonthValue();
int day = ld.getDayOfMonth();
System.out.println(month + " " + day + " " + year);

Prints

5 6 2020

Check out the other date/time related classes in the java.time package.




回答2:


It's much better to use the new api as answered by WJS but if for some reason you want to use the old api you should use Calendar

SimpleDateFormat formatter = new SimpleDateFormat("yyyy/MM/dd");
formatter.parse("2020/11/06");
Calendar calendar = formatter.getCalendar();

int day = calendar.get(Calendar.DAY_OF_MONTH);
int month = calendar.get(Calendar.MONTH) + 1; // add 1 because it returns 0-11
int year = calendar.get(Calendar.YEAR);

System.out.println(day);
System.out.println(month);
System.out.println(year);


来源:https://stackoverflow.com/questions/62643131/how-to-extract-day-month-and-year-from-date-using-java

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!