Sunday, 17 August 2014

Java Date and Calendar Examples

 Date Examples and Conversions:--


             In this post shows you how to work with java.util.Date() and java.util.Calendar examples and also to conversions.
            Date is sufficient if you need only a current timestamp in your application, and you do not need to operate on dates, e.g., one-week later. You can further use SimpleDateFormat to control the date/time display format.

If you want to display the current system date using the Date() class is as follows,

                 java.util.Date date = new java.util.Date();

                 System.out.println(date);

In this code you will get output:- Sun Aug 10 00:59:22 IST 2014.
Here you will get Week,Month,Day,Time,Region and Year.

 Some common date and time patterns used in the java.text.SimpleDateFormat are

       d      -       indicates day 1 to 31,
      dd     -       indicates day in two digits including zero e.g 01 to 31.
       E     -       Day name in week e.g Monday,Tuesday and so on.
       M    -       indicates Month e.g 1 to 12,MM indicates month in two digits like 01 to 12
                               MMM  -   indicates month in words e.g Jan,Feb,Mar and so on
                               MMMM - indicates month in full words e.g Janaury,February and so..
       y        -     indicates Year e.g 2014
       a        -     am/pm Marker e.g AM/PM.
       H       -     hour in day e.g 0-23.
       h        -     hour in am/pm e.g 1-12.
       m       -     minute in hour 0-60.
       s         -    second in minute 0-60.

If you want to display only specific Date format then use SimpleDateFormat,

             SimpleDateFormat  sdf = new SimpleDateFormat("dd/MM/yyyy");

             String date = sdf.format(new java.util.Date());
             System.out.println(date);

The output- 05/10/2014.

    Date with time example,

            SimpleDateFormat  sdf = new SimpleDateFormat("dd/MM/yyyy  hh:mm:ss");
            String date = sdf.format(new java.util.Date());
            System.out.println(date);

The output- 05/10/2014 01:10:29

            The above example is to converting the Date into String. Next see how to convert the String into Date Format using  SimpleDateFormat,

            String date = "20/07/2014";
            SimpleDateFormat  sdf = new SimpleDateFormat("dd/MM/yyyy");
            System.out.println(sdf.parse(date));           //parse method can convert string to date

The output-Sun Jul 20 00:00:00 IST 2014.

    The above sdf.parse(date) returns the Date object with specified date format.

Summary of Date class:
  •  Date  class is sufficient if you just need a simple timestamp.                                                                  
  • You could use SimpleDateFormat to control the date/time display format.
        Use java.text.DateFormat to format a Date (form Date to text) and parse a date string (from text to Date). SimpleDateFormat is a subclass of DateFormat.

      Date is legacy class, which does not support internationalization. Calendar and DateFormat support locale (you need to consider locale only if you program is to be run in many countries concurrently).

         Use java.util.Calendar class if you need to extract year, month, day, hour, minute, and second, or manipulating these field (e.g., 7 days later, 3 weeks earlier).  Next we can discuss Calendar examples.


DateFormat Examples:

 

          java.text.DateFormat is an abstract class for formats (from date to text) and parses (from text to date) date/time in a text-language-independent manner. SimpleDateFormat is an implementation subclass. Date formatter operates on Date object.

      To use the date formatter, first create a DateFormat object for the desired date/time format, and then use the format() method to produce a date/time string. 

To use the DateFormat, use one of these static factory method to create an instance:  

    DateFormat.getDateTimeInstance(): use the default style and locale to format date and time.                 DateFormat.getDateTimeInstance(int dateStyle, int timeStyle, Locale aLocale): style  include 
                                            DateFormat.FULL, LONG, MEDIUM, and SHORT.
    DateFormat.getInstance():     uses SHORT style for date and time.
    DateFormat.getDateInstance(), DateFormat.getDateInstance(int style, Locale aLocale):  date only.
    DateFormat.getTimeInstance(), DateFormat.getTimeInstance(int style, Locale aLocale):   time only.

Example:
                 import java.util.Date;
                 import java.text.DateFormat;
                 import java.text.SimpleDateFormat;
                 import java.util.Locale;
                
                 public class DateFormatExample{
                         public static void main(String[] args) {

                                  Date date = new Date();
                                                   // Use DateFormat
                                  DateFormat formatter = DateFormat.getInstance(); // Date and time
                                  String dateStr = formatter.format(date);
                                  System.out.println(dateStr);
                                  formatter = DateFormat.getTimeInstance();        // time only
                                  System.out.println(formatter.format(date));
                                                    // Use locale
                                  formatter = DateFormat.getDateTimeInstance(DateFormat.FULL,                                                                         DateFormat.FULL, Locale.ENGLISH);
                                  System.out.println(formatter.format(date));
 
                         }
                 }

    Output--
                                         8/17/14 10:58 PM
                                         10:59:19 PM
                                         Sunday, August 17, 2014 11:01:27 PM IST

Calendar Examples:--

 The Calendar class provides support for:

    1) maintaining a set of calendar fields such as YEAR, MONTH, DAY_OF_MONTH, HOUR ,                                                                             MINUTE, SECOND, MILLISECOND; and

    2)  manipulating these calendar fields, such as getting the date of the previous week,next week,next 
         month and so on.

Calendar provides internationalization support.

            Calendar is a abstract class, and you cannot use the constructor to create an instance. Instead, you use the static method Calendar.getInstance() to instantiate an implementation sub-class.

     Calendar.getInstance(): return a Calendar instance based on the current time in the default time zone with the default locale.
    Calendar.getInstance(TimeZone zone)
    Calendar.getInstance(Locale aLocale)
    Calendar.getInstance(TimeZone zone, Locale aLocale)

Some of the usefull calendar fields are as follows,

        Calendar.YEAR                      -  Identifies the year.
        Calendar.MONTH                   - Identifies the month.
        Calendar.DAY_OF_MONTH  - Identifies the day.
        Calendar.HOUR                       - Identifies the hour.
        Calendar.MINUTE                   - Identifies the minute.
        Calendar.SECOND                  - Identify the second.

Example:-
                    import java.text.SimpleDateFormat;
                    import java.util.Calendar;

                    public class CalendarExample {
                           public static void main(String[] args) {
                                     // Get an instance of a Calendar, using the current time.
                                  SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd                                                                                                               HH:mm:ss");
                                  Calendar calendar = Calendar.getInstance();
                                  System.out.println(dateFormat.format(calendar.getTime()));
                                       // Printing some information...
                                  System.out.println("ERA: " + calendar.get(Calendar.ERA));
                                  System.out.println("YEAR: " + calendar.get(Calendar.YEAR));
                                  System.out.println("MONTH: " + calendar.get(Calendar.MONTH));                
                                  System.out.println("WEEK_OF_YEAR: "+
                                                                  calendar.get(Calendar.WEEK_OF_YEAR));
                                  System.out.println("WEEK_OF_MONTH: " +                   
                                                                  calendar.get(Calendar.WEEK_OF_MONTH));
                                  System.out.println("DATE: " + calendar.get(Calendar.DATE));
                                  System.out.println("DAY_OF_MONTH: " 
                                                                        +calendar.get(Calendar.DAY_OF_MONTH));
                                  System.out.println("DAY_OF_YEAR: " + 
                                                                 calendar.get(Calendar.DAY_OF_YEAR));
                                  System.out.println("DAY_OF_WEEK: " +    
                                                                 calendar.get(Calendar.DAY_OF_WEEK));
                                  System.out.println("DAY_OF_WEEK_IN_MONTH: " +  
                                                                 calendar.get(Calendar.DAY_OF_WEEK_IN_MONTH));
                                  System.out.println("AM_PM: " + calendar.get(Calendar.AM_PM));
                                  System.out.println("HOUR: " + calendar.get(Calendar.HOUR));
                                  System.out.println("HOUR_OF_DAY: " + 
                                                                 calendar.get(Calendar.HOUR_OF_DAY));
                                  System.out.println("MINUTE: " + calendar.get(Calendar.MINUTE));
                                  System.out.println("SECOND: " + calendar.get(Calendar.SECOND));
                                  System.out.println("MILLISECOND: " +   
                                                                         calendar.get(Calendar.MILLISECOND));
                        }
              }

A sample execution is shown below:

2014-02-06 17:33:40
ERA: 1
YEAR: 2014
MONTH: 1
WEEK_OF_YEAR: 6
WEEK_OF_MONTH: 2
DATE: 6
DAY_OF_MONTH: 6
DAY_OF_YEAR: 37
DAY_OF_WEEK: 5
DAY_OF_WEEK_IN_MONTH: 1
AM_PM: 1
HOUR: 5
HOUR_OF_DAY: 17
MINUTE: 33
SECOND: 40
MILLISECOND: 692

Manipulating the Calendar dates:

         If you want to add or substract the days from the existing calendar then,

                       Calendar cal = Calendar.getInstance();
                       System.out.println("The current date is: "+cal.getTime());
                       cal.add(Calendar.DATE, 2);                                  //added two days
                       System.out.println("After adding 2 days: "+cal.getTime());
                       cal.add(Calendar.Date,-8);
                       System.out.println("After substracting 8 days: "+cal.getTime());

output--
                      The current date is: Wed Aug 27 15:00:56 IST 2014
                      After adding 2 days: Fri Aug 29 15:00:56 IST 2014
                      After substracting 8 days: Thu Aug 21 15:28:50 IST 2014

        If you want to add or substract the month from the existing calendar then,

                      Calendar cal = Calendar.getInstance();
                      System.out.println("The current date is: "+cal.getTime());
                      cal.add(Calendar.MONTH, 4);                //After 4 months
                      System.out.println("After 4 months : "+cal.getTime());
                      cal.add(Calendar.MONTH, -6)                //6 months ago
                      System.out.println("6 months ago : "+cal.getTime());

output-
                     The current date is: Wed Aug 27 15:00:56 IST 2014
                    After 4 months : Sat Dec 27 15:37:02 IST 2014
                    6 months ago :Fri Jun 27 15:37:02 IST 2014

Samething follow for other calendar fields like year,day,day of week and so on.

Converting Date Object to Calendar Object :-

                 SimpleDateFormat sdf = new SimpleDateFormat("dd/MM/yyyy");
                 String dateStr = "10/10/2014";
                 Date date = sf.parse(dateStr);
                 Calendar cal = Calendar.getInstance();
                 cal.setTime(date);
                 System.out.println(cal.getTime());

Setting the Calendar fields:-

                  Calendar cal = Calendar.getInstance();
                  System.out.println("The current date is: "cal.getTime());
                  cal.set(Calendar.MINUTE, 25);
                  cal.set(Calendar.DAY_OF_MONTH, 10);
                  cal.set(Calendar.YEAR, 2013);
                  System.out.println("After setting: "cal.getTime());
output-
                 The current date is: Wed Aug 27 16:04:21 IST 2014
                 After setting: Sat Aug 10 16:25:21 IST 2013

 

java.util.GregorianCalendar:-


                   The calendar that we use today, called Gregorian calendar, came into effect in October 15, 1582 in some countries and later in other countries. It replaces the Julian calendar. 10 days were removed from the calendar, i.e., October 4, 1582 (Julian) was followed by October 15, 1582 (Gregorian). The only difference between the Gregorian and the Julian calendar is the "leap-year rule". In Julian calendar, every four years is a leap year. In Gregorian calendar, a leap year is a year that is divisible by 4 but not divisible by 100, or it is divisible by 400, i.e., the Gregorian calendar omits century years which are not divisible by 400 (removing 3 leap years (or 3 days) for every 400 years). Furthermore, Julian calendar considers the first day of the year as march 25th, instead of January 1st.

                    java.util.Calendar is an abstract class. Calendar.getInstance() returns an implementation class java.util.GregorianCalendar (except locales of "th" and "jp"). In Java, this GregorianCalendar handles both the Gregorian calendar as well as the Julian calendar, including the cut over.