JAVA Calendar Examples

Program to Display Month of the year.

package com.arun.calendar;
import java.util.Calendar;

public class DisplayMonthOfYear {

  public static void main(String[] args) {
 
    //create Calendar instance
    Calendar now = Calendar.getInstance();
 
    System.out.println("Current date : " + (now.get(Calendar.MONTH) + 1)
                        + "-"
                        + now.get(Calendar.DATE)
                        + "-"
                        + now.get(Calendar.YEAR));
 
    //create an array of months
    String[] strMonths = new String[]{
                      "Jan",
                      "Feb",
                      "Mar",
                      "Apr",
                      "May",
                      "Jun",
                      "Jul",
                      "Aug",
                      "Sep",
                      "Oct",
                      "Nov",
                      "Dec"
                    };
  /*Calendar.MONTH instance gives current month number starting from 0 - 11. so 0 is 'Jan'  and
11 is 'Dec'. Hence we don't add +1 in MONTH while we added in display because in written 1 is 'Jan' and 12 is 'Dec'.
*/
    System.out.println("Current month is : " +
                strMonths[now.get(Calendar.MONTH)]
              );
 

  }

}

/*
Output would be
Current date : 11-9-2014
Current month is : Nov

*/
--------------------------------------------------------------------------------------------------------------------------

Simple Calendar Example

package com.arun.calendar;

import java.util.Calendar;

public class JavaSimpleCalendarExample {

  public static void main(String[] args) {
 
    //use getInstance() method to get object of java Calendar class
    Calendar cal = Calendar.getInstance();
 
    //use getTime() method of Calendar class to get date and time
    System.out.println("Today is : " + cal.getTime());
  }
}

/*
TYPICAL Output would be
Today is : Sun Nov 09 14:54:53 IST 2014
*/

No comments:

Post a Comment