Get Day, Month, Year, Day of week etc from date in JAVA

Many times in your project you might need each part of date separately. For example I wanted to show date with a different format in my android app (see image below).

So for above I wanted day, month and year separately which I can get using get and getDisplayName method of Calender class.

Below is a sample code to get day part of the date object using calender object:

public int getDayFromDate(Date date)
 {
            Calendar cal = Calendar.getInstance();
     cal.setTime(date);
     return cal.get(Calendar.DAY_OF_MONTH);
 }

Similarly we can get year of the date just by replacing Calendar.DAY_OF_MONTH with Calendar.YEAR.

For getting month and day of the week from date object these is a different method that is by using getDisplayName method.

public String getMonthFromDate(Date date)
 {
            Calendar cal = Calendar.getInstance();
     cal.setTime(date);
     return cal.getDisplayName (Calendar.MONTH);
 }

Similarly we can also get day of the week from date object and for that we just have to replace Calendar.MONTH with Calendar.DAY_OF_WEEK.

Similarly for all those date part which are in string format we have to call getDisplayName method and for others which are expacted to be integer we should call get method.

I hope this information will help beginner JAVA developers as well as some intermediate. Stay tuned with us to get more useful articles and codes.

Leave a Reply

Your email address will not be published.