-1
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.

  • 2
    _its not working._ What does that mean? Please provide a [mcve], and see [ask], [help/on-topic]. – AMC Jun 29 '20 at 17:51
  • Probably expecting the day of the month? IIRC in Java and JS it's `getDate`. – José Pedro Jun 29 '20 at 19:58
  • 1
    I recommend you don’t use `SimpleDateFormat` and `Date`. Those classes are poorly designed and long outdated, the former in particular notoriously troublesome. Instead use `LocalDate` and `DateTimeFormatter`, both from [java.time, the modern Java date and time API](https://docs.oracle.com/javase/tutorial/datetime/). – Ole V.V. Jun 30 '20 at 05:38
  • [I downvoted because "it's not working" is not helpful](http://idownvotedbecau.se/itsnotworking/). – Ole V.V. Jun 30 '20 at 05:38
  • Even if you insisted on using `Date`, you should still stay far away from the deprecated `getXxxx`methods. They have been deprecated since February 1997 because they work unreliably across time zones. – Ole V.V. Jun 30 '20 at 05:41

2 Answers2

2

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.

WJS
  • 36,363
  • 4
  • 24
  • 39
0

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);
Oleg
  • 6,124
  • 2
  • 23
  • 40