-2

Using the Calendar API I want to store the date of object creation in its instance field. The object is then saved to a text file.

Calendar cal = Calendar.getInstance();
Date todaysDate = cal.getTime();
Object obj = new Object(todaysDate);

Later, I want to return the month the object was created. However, the date was stored as type 'Date'and AFAIK the Date API doesn't have a method to return the month.

Is there a way to store the date in a variable that allows me to use Calendar methods?

2 Answers2

0

Something like this. Get Calendar from Date. Month number is started from 0

// current date
Date todaysDate = calendar.getTime();
Calendar calendar = new GregorianCalendar();

// Init `Calendar` from `Date`
calendar.setTime(todaysDate);

// Get month nimber from `Calendar` object 
final int monthNumber = calendar.get(Calendar.MONTH);
Ashot Karakhanyan
  • 2,804
  • 3
  • 23
  • 28
0

Try this my friend

  public static void main(String[] args) {


        Calendar cal = Calendar.getInstance();
        Date todaysDate = cal.getTime();
            int month = todaysDate.getMonth()+1;
            System.out.println(month);

    }
Girish
  • 1,717
  • 1
  • 18
  • 30