问题
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