Monday, November 11, 2013

getting day, month and year form java.util.Date

You may be trying to get for example the day, month and year from the java.util.Date directly such as:
Date date;
          int day =  date.getDay();
          int month = date.getMonth();
          int year = date.getYear();

         Just know that this previous way of getting them (d,m,y) is deprecated and only lead you to mess. However you should rather use the Calendar to get what you want from the date object, and here is how:

 Date date;
 Calendar calendar = Calendar.getInstance();
 calendar.setTime(date);
 int day = calendar.get(Calendar.DAY_OF_MONTH);
 int month= calendar.get(Calendar.MONTH);
 int year= calendar.get(Calendar.YEAR);

Hope you feel released...

Note: Of course importing from java.util.*;

No comments:

Post a Comment