Home > Programming > Use Calendar instead of Date in Java

Use Calendar instead of Date in Java

January 14th, 2009 Leave a comment Go to comments

Common Issue

When you use java.util.Date object with JDK version higher than 1.1

Date d = new Date();
d.getMonth();

You will get deprecated warning messages when you try to compile

The method getMonth() from the type Date is deprecated

However you can supress the warning message by adding @SuppressWarnings("deprecation") to you main() method

@SuppressWarnings("deprecation")
public static void main(String[] args) {
    ...
}

or adding @SuppressWarnings("unchecked") to other method

@SuppressWarnings("unchecked")
public void otherMethod() {
    ...
}

Note that this can only be used in JDK 5.0+

Alternative

Now let’s forget about working around the deprecated method, let’s learn how to use java.util.Calendar instead

Example code below is showing you how to use Calendar object and format the date in the way you required.

Class: TestCalendar.java

import java.text.SimpleDateFormat;
import java.util.Calendar;
 
public class TestCalendar {
 
    public static void main(String[] args) {
        Calendar current = Calendar.getInstance();
        Calendar last6month = Calendar.getInstance();
        last6month.set(Calendar.MONTH, current.get(Calendar.MONTH) - 6);
 
        SimpleDateFormat dformatter = new SimpleDateFormat(
                "dd/MM/yyyy HH:MM:SS a");
 
        System.out.println("Calendar Object: " + current);
        System.out.println("Default Date: " + current.getTime());
        System.out.println("User Formatted Date: "
                + dformatter.format(current.getTime()));
    }
 
}

Output of this program

Calendar Object: java.util.GregorianCalendar[time=1231889016972,
  areFieldsSet=true,areAllFieldsSet=true,lenient=true,
  zone=sun.util.calendar.ZoneInfo[id="Australia/Sydney",offset=36000000,
  dstSavings=3600000,useDaylight=true,transitions=142,
  lastRule=java.util.SimpleTimeZone[id=Australia/Sydney,offset=36000000,
  dstSavings=3600000,useDaylight=true,startYear=0,startMode=2,startMonth=9,
  startDay=-1,startDayOfWeek=1,startTime=7200000,startTimeMode=1,endMode=2,
  endMonth=2,endDay=-1,endDayOfWeek=1,endTime=7200000,endTimeMode=1]],
  firstDayOfWeek=1,minimalDaysInFirstWeek=1,ERA=1,YEAR=2009,MONTH=0,
  WEEK_OF_YEAR=3,WEEK_OF_MONTH=3 DAY_OF_MONTH=14,DAY_OF_YEAR=14,
  DAY_OF_WEEK=4,DAY_OF_WEEK_IN_MONTH=2,AM_PM=0,HOUR=10,HOUR_OF_DAY=10,
  MINUTE=23,SECOND=36,MILLISECOND=972,ZONE_OFFSET=36000000,
  DST_OFFSET=3600000]
Default Date: Wed Jan 14 10:23:36 EST 2009
User Formatted Date: 14/01/2009 10:01:972 AM
Advertisement ยป Recommended Java book Java How to Program, 7th Edition ( by Harvey M. Deitel, Paul J. Deitel )
Categories: Programming
  1. No comments yet.
  1. No trackbacks yet.