DATE AND TIME MANIPULATION
CONTENTS
1.   Overview
2.   Understanding Date Class
       •   Declaring, Creating, getting and Printing dates and time
1.   Date and Time operations
       •   Comparing dates
1.   Formating Dates
       •   Printing dates according to required format
CONTENTS
5.   Understanding Calendar Class
       •      Declaring, Creating, getting,setting and Printing Calendar objects
5.   Calendar Operations
           • Extracting,adding and rolling the Calendar fields
5.   Undarstanding GregoreanCalendar
WORKING WITH DATE CLASS
WHAT IS DATE CLASS?
•   Java provides the Date class available in java.util package, this class encapsulates the current
    date and time.
•   The Date class supports two constructors. The first constructor initializes the object with the
    current date and time.
•   The following constructor accepts one argument that equals the number of milliseconds that
    have elapsed since midnight, January 1, 1970

             Date( )
             Date(long millisec )
DATE CLASS METHODS
•   Once you have a Date object available, you can call any of the following support methods to
    play with dates:
GETTING CURRENT DATE & TIME
•    This is very easy to get current date and time in Java. You can use a simple Date object
     with toString()method to print current date and time as follows:



    import java.util.Date;
    public class DateDemo {
          public static void main(String args[]) {
          Date date=new Date();
          System.out.println(date);
          }
    }
    This would produce following result:

    Mon Mar 04 00:04:41 PST 2013
DATE COMPARISON:

•    There are following three ways to compare two dates:
      • You can use getTime( ) to obtain the number of milliseconds that have elapsed since
        midnight, January 1, 1970, for both objects and then compare these two values.
      • You can use the methods before( ), after( ), and equals( ). Because the 12th of the
        month comes before the 18th, for example, new Date(99, 2, 12).before(new Date (99,
        2, 18)) returns true.
      • You can use the compareTo( ) method, which is defined by the Comparable interface
        and implemented by Date.
COMPARING DATES
import java.util.Date;
public class DateDemo {
      public static void main(String args[]) {
      Date date1=new Date();
      Date date2=new Date();
      System.out.println(date1.equals(date2));
      System.out.println(date1.after(date2));
      System.out.println(date1.before(date2));
      System.out.println(date1.compareTo(date2));

           }
}
This would produce following result:
true
false
false
0
FORMATING DATES
DATE FORMATTING USING SIMPLEDATEFORMAT:
•   SimpleDateFormat is a concrete class for formatting and parsing dates in a locale-sensitive
    manner. SimpleDateFormat allows you to start by choosing any user-defined patterns for
    date-time formatting. For example:

import java.util.*;
import java.text.*;
public class DateDemo {
   public static void main(String args[]) {
   Date dNow = new Date( );
   SimpleDateFormat ft =
   new SimpleDateFormat ("E yyyy.MM.dd 'at' hh:mm:ss a zzz");
   System.out.println("Current Date: " + ft.format(dNow));
   }
}


This would produce following result:

Current Date: Mon 2013.03.04 at 12:05:35 AM PST
SIMPLE DATEFORMAT FORMAT CODES:
•   To specify the time format use a time pattern string. In this pattern, all ASCII letters are
    reserved as pattern letters, which are defined as the following:
Character             Description    Example
        G             Era designator AD
        y             Year in four digits    2001
        M             Month in year July or 07
        d             Day in month   10
        h             Hour in A.M./P.M. (1~12)      12
        H             Hour in day (0~23)     22
        m             Minute in hour 30
        s             Second in minute       55
        S             Millisecond    234
        E             Day in week    Tuesday
        D             Day in year    360
        F             Day of week in month 2 (second Wed. in July)
        w             Week in year   40
        W             Week in month 1
        a             A.M./P.M. marker       PM
        k             Hour in day (1~24)     24
        K             Hour in A.M./P.M. (0~11)      10
        z             Time zone      Eastern Standard Time
        '             Escape for text        Delimiter
        "             Single quote   `
DATE FORMATTING USING PRINTF():
•    Date and time formatting can be done very easily using printf method. You use a two-letter
     format, starting with t and ending in one of the letters of the table given below. For
     example:

import java.util.Date;

public class DateDemo {

    public static void main(String args[]) {
    Date date = new Date();
    String str = String.format("Current Date/Time : %tc", date );
    System.out.printf(str);
    }
}


This would produce following result:

Current Date/Time : Mon Mar 04 00:06:20 PST 2013
DATE FORMATTING USING PRINTF():
•   It would be a bit silly if you had to supply the date multiple times to format each part. For
    that reason, a format string can indicate the index of the argument to be formatted.
•   The index must immediately follow the %, and it must be terminated by a $. For example:

import java.util.Date;

public class DateDemo {

    public static void main(String args[]) {
    Date date = new Date();
    System.out.printf("%1$s %2$tB %2$td, %2$tY","Due date:", date);
    }
}


This would produce following result:

Due date: March 04, 2013
DATE FORMATTING USING PRINTF():
•   Alternatively, you can use the < flag. It indicates that the same argument as in the
    preceding format specification should be used again. For example:

import java.util.Date;

public class DateDemo {

    public static void main(String args[]) {
    Date date = new Date();
    System.out.printf("%s %tB %<te, %<tY","Due date:", date);
    }
}




This would produce following result:

Due date: March 4, 2013
DATE AND TIME CONVERSION CHARACTERS:
•   To specify the time format use a time pattern string. In this pattern, all ASCII letters are
    reserved as pattern letters, which are defined as the following:
Character   Description                                              Example
c           Complete date and time                                   Mon May 04 09:51:52 CDT 2009
F           ISO 8601 date                                            2004-02-09
D           U.S. formatted date (month/day/year)                     02/09/2004
T           24-hour time                                             18:05:19
r           12-hour time                                             06:05:19 pm
R           24-hour time, no seconds                                 18:05
Y           Four-digit year (with leading zeroes)                    2004
y           Last two digits of the year (with leading zeroes)        04
C           First two digits of the year (with leading zeroes)       20
B           Full month name                                          February
b           Abbreviated month name                                   Feb
n           Two-digit month (with leading zeroes)                    02
d           Two-digit day (with leading zeroes)                      03
e           Two-digit day (without leading zeroes)                   9
A           Full weekday name                                        Monday
a           Abbreviated weekday name                                 Mon
j           Three-digit day of year (with leading zeroes)            069
H           Two-digit hour, between 00 and 23                        18
k           Two-digit hour, between 0 and 23                         18
I           Two-digit hour, between 01 and 12                        06
l           Two-digit hour, between 1 and 12 6
M           Two-digit minutes (with leading zeroes)                  05
S           Two-digit seconds (with leading zeroes)                  19
L           Three-digit milliseconds (with leading zeroes)           047
N           Nine-digit nanoseconds (with leading zeroes)             047000000
P           Uppercase morning or afternoon marker                    PM
p           Lowercase morning or afternoon marker                    pm
z           RFC 822 numeric offset from GMT                          -0800
Z           Time zone                                                PST
s           Seconds since 1970-01-01 00:00:00 GMT                    1078884319
Q           Milliseconds since 1970-01-01 00:00:00 GMT               1078884319047
PARSING STRINGS INTO DATES:
•    The SimpleDateFormat class has some additional methods, notably parse( ) , which tries to
     parse a string according to the format stored in the given SimpleDateFormat object. For
     example:
import java.util.*;
import java.text.*;
public class DateDemo {
public static void main(String args[]) {
      SimpleDateFormat ft = new SimpleDateFormat ("yyyy-MM-dd");
               String sdate="2013-03-08";
               Date t= ft.parse(sdate);
               System.out.println(t);
}
}



This would produce following result:


Fri Mar 08 00:00:00 PST 2013
SLEEPING FOR A WHILE:
•    You can sleep for any period of time from one millisecond up to the lifetime of your
     computer. For example, following program would sleep for 5 seconds:

import java.util.*;
import java.text.*;
public class DateDemo {
public static void main(String args[])throws Exception {
      System.out.println(new Date( ) + "");
      Thread.sleep(5000);
      System.out.println(new Date( ) + "");
  }
}




This would produce following result:

Mon Mar 04 00:32:29 PST 2013
Mon Mar 04 00:32:34 PST 2013
MEASURING ELAPSED TIME:
•    Sometime you may need to measure point in time in milliseconds. So let's re-write above
     example once again:
import   java.util.*;
import   java.text.*;
public   class DateDemo {
public   static void main(String args[])throws Exception {
          long start = System.currentTimeMillis( );
          System.out.println(new Date( ) + "");
          Thread.sleep(5000);
          System.out.println(new Date( ) + "");
          long end = System.currentTimeMillis( );
          long diff = end - start;
          System.out.println("Difference is : " + diff);
 }
}



This would produce following result:

Mon Mar 04 00:37:43 PST 2013
Mon Mar 04 00:37:48 PST 2013
Difference is : 5054
THE CALENDAR CLASS
•   The Calendar class is an abstract class that provides methods for converting between a specific
    instant in time and a set of calendar fields such as YEAR, MONTH, DAY_OF_MONTH, HOUR, and
    so on, and for manipulating the calendar fields, such as getting the date of the next week. An instant
    in time can be represented by a millisecond value that is an offset from the Epoch, January 1, 1970
    00:00:00.000 GMT (Gregorian).


•   The class also provides additional fields and methods for implementing a concrete calendar system
    outside the package. Those fields and methods are defined as protected.


•   Like other locale-sensitive classes, Calendar provides a class method, getInstance, for getting a
    generally useful object of this type. Calendar's getInstance method returns a Calendar object whose
    calendar fields have been initialized with the current date and time:


•      Calendar rightNow = Calendar.getInstance();
CALENDAR CLASS FIELDS
static int AM_PM
                     Field number for get and set indicating whether the HOUR is before or after noon.
static int APRIL
                Value of the MONTH field indicating the fourth month of the year in the Gregorian and Julian calendars.
static int AUGUST
                Value of the MONTH field indicating the eighth month of the year in the Gregorian and Julian calendars.
static int DATE
                Field number for get and set indicating the day of the month.
static int DAY_OF_MONTH
                Field number for get and set indicating the day of the month.
static int DAY_OF_WEEK
                Field number for get and set indicating the day of the week.
static int DAY_OF_WEEK_IN_MONTH
                Field number for get and set indicating the ordinal number of the day of the week within the current month.
static int DAY_OF_YEAR
                Field number for get and set indicating the day number within the current year.
static int DECEMBER
                Value of the MONTH field indicating the twelfth month of the year in the Gregorian and Julian calendars.
static int ERA
                Field number for get and set indicating the era, e.g., AD or BC in the Julian calendar.
static int FEBRUARY
                Value of the MONTH field indicating the second month of the year in the Gregorian and Julian calendars.
static int FRIDAY
                     Value of the DAY_OF_WEEK field indicating Friday.
static int HOUR
                Field number for get and set indicating the hour of the morning or afternoon.
static int HOUR_OF_DAY
                Field number for get and set indicating the hour of the day.
static int JANUARY
                Value of the MONTH field indicating the first month of the year in the Gregorian and Julian calendars.
static int JULY
                Value of the MONTH field indicating the seventh month of the year in the Gregorian and Julian calendars.
static int JUNE
                Value of the MONTH field indicating the sixth month of the year in the Gregorian and Julian calendars.
static int MARCH
                Value of the MONTH field indicating the third month of the year in the Gregorian and Julian calendars.
static int MAY
                Value of the MONTH field indicating the fifth month of the year in the Gregorian and Julian calendars.
static int MINUTE
                Field number for get and set indicating the minute within the hour.
static int MONDAY
                Value of the DAY_OF_WEEK field indicating Monday.
static in MONTH 
        t           Field number for get and set indicating the month.
static in NOVEMBER
        t     Value of the MONTH field indicating the eleventh month of the year in the Gregorian and Julian calendars.
static in OCTOBER
        t     Value of the MONTH field indicating the tenth month of the year in the Gregorian and Julian calendars.
static in SATURDAY
        t     Value of the DAY_OF_WEEK field indicating Saturday.
static in SECOND
        t     Field number for get and set indicating the second within the minute.
static in SEPTEMBER
        t     Value of the MONTH field indicating the ninth month of the year in the Gregorian and Julian calendars.
static in SUNDAY
        t     Value of the DAY_OF_WEEK field indicating Sunday.
static in THURSDAY
        t     Value of the DAY_OF_WEEK field indicating Thursday.
static in TUESDAY
        t     Value of the DAY_OF_WEEK field indicating Tuesday.
static in WEDNESDAY
        t     Value of the DAY_OF_WEEK field indicating Wednesday.
static in WEEK_OF_MONTH
        t     Field number for get and set indicating the week number within the current month.
static in WEEK_OF_YEAR
        t     Field number for get and set indicating the week number within the current year.
static in YEAR
        t      Field number for get and set indicating the year.
CALENDAR CLASS METHODS
Method Summary
   abstract  void add(int field, int amount) Adds or subtracts the specified amount of time to the given calendar field, based on
                   the calendar's rules.
         boolean after(Object when) Returns whether this Calendar represents a time after the time represented by the
                   specified Object.
         boolean before(Object when) Returns whether this Calendar represents a time before the time represented by the
                   specified Object.
               int compareTo(Calendar anotherCalendar) Compares the time values (millisecond offsets from the Epoch)
                   represented by two Calendar objects.
         boolean equals(Object obj) Compares this Calendar to the specified Object.
               int get(int field) Returns the value of the given calendar field.
  static Calendar getInstance() Gets a calendar using the default time zone and locale.
             Date getTime() Returns a Date object representing this Calendar's time value (millisecond offset from the Epoch).

              long getTimeInMillis() Returns this Calendar's time value in milliseconds.
              void roll(int field, int amount) Adds the specified (signed) amount to the specified calendar field without changing
                   larger fields.
              void set(int field, int value) Sets the given calendar field to the given value.
              void set(int year, int month, int date) Sets the values for the calendar fields YEAR, MONTH, and DAY_OF_MONTH.
THE CALENDAR CLASS
•   Getting the value of the fields
•   The following field names can be used as an argument to the Calendar.get() method.
•   Access Method                                        Meaning
•   calob.get(Calendar.YEAR)                             int value of the year
•   calob.get(Calendar.MONTH)                            int value of the month (0-11)
•   calob.get(Calendar.DAY_OF_MONTH)                     int value of the day of the month (1-31)
•   calob.get(Calendar.DAY_OF_WEEK)                      int value of the day of the week (0-6)
•   calob.get(Calendar.HOUR)                             int value of the hour in 12 hour notation (0-12)
•   calob.get(Calendar.AM_PM)                            returns either Calendar.AM or Calendar.PM
•   calob.get(Calendar.HOUR_OF_DAY)                      int value of the hour of the day in 24-hour notation (0-24)
•   calob.get(Calendar.MINUTE)                           int value of the minute in the hour (0-59)
•   calob.get(Calendar.SECOND)                           int value of the second within the minute (0-59).
•   calob.get(Calendar.MILLISECOND)                      int value of the milliseconds within a second (0-999).
•    Code Snippet for getting calendar fields.
import java.util.*;
import java.text.*;
public class DateDemo {
public static void main(String args[])throws Exception {
      Calendar cal = Calendar.getInstance();
      // You cannot use Date class to extract individual Date fields
      int year = cal.get(Calendar.YEAR);
      int month = cal.get(Calendar.MONTH);      // 0 to 11
      int day = cal.get(Calendar.DAY_OF_MONTH);
      int hour = cal.get(Calendar.HOUR_OF_DAY);
      int minute = cal.get(Calendar.MINUTE);
      int second = cal.get(Calendar.SECOND);
      System.out.printf("Now is %d/%d/%d %d:%d:%dn",
                          year,month+1, day, hour, minute, second);
}
}

This would produce following result:

Now is 2013/3/5 0:39:48
THE CALENDAR CLASS
•   Setting the value of the fields
•   The following field names can be used as an argument to the Calendar.set() method.
•   Access Method                                        Meaning
•   calob.set(Calendar.YEAR,2013)                        int value of the year
•   calob.set(Calendar.MONTH,1)                          int value of the month (0-11)
•   calob.set(Calendar.DAY_OF_MONTH,1)                   int value of the day of the month (1-31)
•   calob.set(Calendar.DAY_OF_WEEK,1) int value of the day of the week (0-6)
•   calob.set(Calendar.HOUR,1)                           int value of the hour in 12 hour notation (0-12)
•   calob.set(Calendar.AM_PM,1)                          returns either Calendar.AM or Calendar.PM
•   calob.set(Calendar.HOUR_OF_DAY,1) int value of the hour of the day in 24-hour notation (0-24)
•   calob.set(Calendar.MINUTE,1)                         int value of the minute in the hour (0-59)
•   calob.set(Calendar.SECOND,1)                         int value of the second within the minute (0-59).
•   calob.set(Calendar.MILLISECOND,1)     int value of the milliseconds within a second (0-999).
•   OR
•   Calob.set(2013, 3, 10)                               int year ,month,day
•    Code Snippet for setting calendar fields.
import java.util.*;
import java.text.*;
public class DateDemo {
public static void main(String args[])throws Exception {
      Calendar cal = Calendar.getInstance();
      // You cannot use Date class to extract individual Date fields
      cal.set(Calendar.YEAR,2014);
      cal.set(Calendar.MONTH,4);       // 0 to 11
      cal.set(Calendar.DAY_OF_MONTH,5);
      cal.set(Calendar.HOUR_OF_DAY,7);
      cal.set(Calendar.MINUTE,3);
      cal.set(Calendar.SECOND,7);
      System.out.println(cal.getTime());
      cal.set(2010,1,1);
      System.out.println(cal.getTime());
      }
}

This would produce following result:
Mon May 05 07:03:07 PDT 2014
Mon Feb 01 07:03:07 PST 2010
THE CALENDAR CLASS
•   Adding the value of the fields
•   The following field names can be used as an argument to the Calendar.add() method.
•   Access Method                                    Meaning
•   calob.add(Calendar.YEAR,1)                       int value of the year
•   calob.add(Calendar.MONTH,1)                      int value of the month (0-11)
•   calob.add(Calendar.DAY_OF_MONTH,1)               int value of the day of the month (1-31)
•   calob.add(Calendar.DAY_OF_WEEK,1)                int value of the day of the week (0-6)
•   calob.add(Calendar.HOUR,1)                       int value of the hour in 12 hour notation (0-12)
•   calob.add(Calendar.AM_PM,1)                      returns either Calendar.AM or Calendar.PM
•   calob.add(Calendar.HOUR_OF_DAY,1)                int value of the hour of the day in 24-hour notation (0-24)
•   calob.add(Calendar.MINUTE,1)                     int value of the minute in the hour (0-59)
•   calob.add(Calendar.SECOND,1)                     int value of the second within the minute (0-59).
•   calob.add(Calendar.MILLISECOND,1)                int value of the milliseconds within a second (0-999).
•    Code Snippet for adding calendar fields.
import java.util.*;
import java.text.*;
public class DateDemo {
public static void main(String args[])throws Exception {
      Calendar cal = Calendar.getInstance();
      // You cannot use Date class to extract individual Date fields
               cal.add(Calendar.YEAR,2);
               cal.add(Calendar.MONTH,4);       // 0 to 11
               cal.add(Calendar.DAY_OF_MONTH,5);
               cal.add(Calendar.HOUR_OF_DAY,7);
               cal.add(Calendar.MINUTE,3);
               cal.add(Calendar.SECOND,7);
               System.out.println(cal.getTime());

        }
}


This would produce following result:
Fri Jul 10 07:53:29 PDT 2015
THE CALENDAR CLASS
•   Substrating the value of the fields
•   The following field names can be used as an argument to the Calendar.add() method.
•   Access Method                                    Meaning
•   calob.add(Calendar.YEAR,-1)                      int value of the year
•   calob.add(Calendar.MONTH,-1)                     int value of the month (0-11)
•   calob.add(Calendar.DAY_OF_MONTH,-1)              int value of the day of the month (1-31)
•   calob.add(Calendar.DAY_OF_WEEK,-1)               int value of the day of the week (0-6)
•   calob.add(Calendar.HOUR,-1)                      int value of the hour in 12 hour notation (0-12)
•   calob.add(Calendar.AM_PM,-1)                     returns either Calendar.AM or Calendar.PM
•   calob.add(Calendar.HOUR_OF_DAY,-1)               int value of the hour of the day in 24-hour notation (0-24)
•   calob.add(Calendar.MINUTE,-1)                    int value of the minute in the hour (0-59)
•   calob.add(Calendar.SECOND,-1)                    int value of the second within the minute (0-59).
•   calob.add(Calendar.MILLISECOND,-1)               int value of the milliseconds within a second (0-999).
•    Code Snippet for substrating calendar fields.
import java.util.*;
import java.text.*;
public class DateDemo {
public static void main(String args[])throws Exception {
      Calendar cal = Calendar.getInstance();
      // You cannot use Date class to extract individual Date fields
               cal.add(Calendar.YEAR,-2);
               cal.add(Calendar.MONTH,-4);       // 0 to 11
               cal.add(Calendar.DAY_OF_MONTH,-5);
               cal.add(Calendar.HOUR_OF_DAY,-7);
               cal.add(Calendar.MINUTE,-3);
               cal.add(Calendar.SECOND,-7);
               System.out.println(cal.getTime());

        }
}


This would produce following result:
Sat Oct 30 17:49:57 PDT 2010
GREGORIANCALENDAR CLASS:
•   GregorianCalendar is a concrete implementation of a Calendar class that implements the
    normal Gregorian calendar with which you are familiar. I did not discuss Calender class in this
    slid, you can look standard Java documentation for this.
•   The getInstance( ) method of Calendar returns a GregorianCalendar initialized with the
    current date and time in the default locale and time zone. GregorianCalendar defines two
    fields: AD and BC. These represent the two eras defined by the Gregorian calendar.
CONSTRUCTORS FOR GREGORIANCALENDAR
 •   There are also several constructors for GregorianCalendar objects:

GregorianCalendar()

Constructs a default GregorianCalendar using the current time in the default
time zone with the default locale.

GregorianCalendar(int year, int month, int date)

Constructs a GregorianCalendar with the given date set in the default
time zone with the default locale.

GregorianCalendar(int year, int month, int date, int hour, int minute)

Constructs a GregorianCalendar with the given date and time set for the default
time zone with the default locale.

GregorianCalendar(int year, int month, int date, int hour, int minute, int
second)

Constructs a GregorianCalendar with the given date and time set for the default
time zone with the default locale.
EXERCISES
 Write a program that takes your Date of Birth, and prints exact years, months, days
    hours, minutes and seconds upto current date.




 Write a program which sets the Expiry date, if current date is Expiry date then terminate
    your program.
 Write a program to create a digital clock.

Date and time manipulation

  • 2.
    DATE AND TIMEMANIPULATION
  • 3.
    CONTENTS 1. Overview 2. Understanding Date Class • Declaring, Creating, getting and Printing dates and time 1. Date and Time operations • Comparing dates 1. Formating Dates • Printing dates according to required format
  • 4.
    CONTENTS 5. Understanding Calendar Class • Declaring, Creating, getting,setting and Printing Calendar objects 5. Calendar Operations • Extracting,adding and rolling the Calendar fields 5. Undarstanding GregoreanCalendar
  • 5.
  • 6.
    WHAT IS DATECLASS? • Java provides the Date class available in java.util package, this class encapsulates the current date and time. • The Date class supports two constructors. The first constructor initializes the object with the current date and time. • The following constructor accepts one argument that equals the number of milliseconds that have elapsed since midnight, January 1, 1970 Date( ) Date(long millisec )
  • 7.
    DATE CLASS METHODS • Once you have a Date object available, you can call any of the following support methods to play with dates:
  • 8.
    GETTING CURRENT DATE& TIME • This is very easy to get current date and time in Java. You can use a simple Date object with toString()method to print current date and time as follows: import java.util.Date; public class DateDemo { public static void main(String args[]) { Date date=new Date(); System.out.println(date); } } This would produce following result: Mon Mar 04 00:04:41 PST 2013
  • 9.
    DATE COMPARISON: • There are following three ways to compare two dates: • You can use getTime( ) to obtain the number of milliseconds that have elapsed since midnight, January 1, 1970, for both objects and then compare these two values. • You can use the methods before( ), after( ), and equals( ). Because the 12th of the month comes before the 18th, for example, new Date(99, 2, 12).before(new Date (99, 2, 18)) returns true. • You can use the compareTo( ) method, which is defined by the Comparable interface and implemented by Date.
  • 10.
    COMPARING DATES import java.util.Date; publicclass DateDemo { public static void main(String args[]) { Date date1=new Date(); Date date2=new Date(); System.out.println(date1.equals(date2)); System.out.println(date1.after(date2)); System.out.println(date1.before(date2)); System.out.println(date1.compareTo(date2)); } } This would produce following result: true false false 0
  • 11.
  • 12.
    DATE FORMATTING USINGSIMPLEDATEFORMAT: • SimpleDateFormat is a concrete class for formatting and parsing dates in a locale-sensitive manner. SimpleDateFormat allows you to start by choosing any user-defined patterns for date-time formatting. For example: import java.util.*; import java.text.*; public class DateDemo { public static void main(String args[]) { Date dNow = new Date( ); SimpleDateFormat ft = new SimpleDateFormat ("E yyyy.MM.dd 'at' hh:mm:ss a zzz"); System.out.println("Current Date: " + ft.format(dNow)); } } This would produce following result: Current Date: Mon 2013.03.04 at 12:05:35 AM PST
  • 13.
    SIMPLE DATEFORMAT FORMATCODES: • To specify the time format use a time pattern string. In this pattern, all ASCII letters are reserved as pattern letters, which are defined as the following: Character Description Example G Era designator AD y Year in four digits 2001 M Month in year July or 07 d Day in month 10 h Hour in A.M./P.M. (1~12) 12 H Hour in day (0~23) 22 m Minute in hour 30 s Second in minute 55 S Millisecond 234 E Day in week Tuesday D Day in year 360 F Day of week in month 2 (second Wed. in July) w Week in year 40 W Week in month 1 a A.M./P.M. marker PM k Hour in day (1~24) 24 K Hour in A.M./P.M. (0~11) 10 z Time zone Eastern Standard Time ' Escape for text Delimiter " Single quote `
  • 14.
    DATE FORMATTING USINGPRINTF(): • Date and time formatting can be done very easily using printf method. You use a two-letter format, starting with t and ending in one of the letters of the table given below. For example: import java.util.Date; public class DateDemo { public static void main(String args[]) { Date date = new Date(); String str = String.format("Current Date/Time : %tc", date ); System.out.printf(str); } } This would produce following result: Current Date/Time : Mon Mar 04 00:06:20 PST 2013
  • 15.
    DATE FORMATTING USINGPRINTF(): • It would be a bit silly if you had to supply the date multiple times to format each part. For that reason, a format string can indicate the index of the argument to be formatted. • The index must immediately follow the %, and it must be terminated by a $. For example: import java.util.Date; public class DateDemo { public static void main(String args[]) { Date date = new Date(); System.out.printf("%1$s %2$tB %2$td, %2$tY","Due date:", date); } } This would produce following result: Due date: March 04, 2013
  • 16.
    DATE FORMATTING USINGPRINTF(): • Alternatively, you can use the < flag. It indicates that the same argument as in the preceding format specification should be used again. For example: import java.util.Date; public class DateDemo { public static void main(String args[]) { Date date = new Date(); System.out.printf("%s %tB %<te, %<tY","Due date:", date); } } This would produce following result: Due date: March 4, 2013
  • 17.
    DATE AND TIMECONVERSION CHARACTERS: • To specify the time format use a time pattern string. In this pattern, all ASCII letters are reserved as pattern letters, which are defined as the following: Character Description Example c Complete date and time Mon May 04 09:51:52 CDT 2009 F ISO 8601 date 2004-02-09 D U.S. formatted date (month/day/year) 02/09/2004 T 24-hour time 18:05:19 r 12-hour time 06:05:19 pm R 24-hour time, no seconds 18:05 Y Four-digit year (with leading zeroes) 2004 y Last two digits of the year (with leading zeroes) 04 C First two digits of the year (with leading zeroes) 20 B Full month name February b Abbreviated month name Feb n Two-digit month (with leading zeroes) 02 d Two-digit day (with leading zeroes) 03 e Two-digit day (without leading zeroes) 9 A Full weekday name Monday a Abbreviated weekday name Mon j Three-digit day of year (with leading zeroes) 069 H Two-digit hour, between 00 and 23 18 k Two-digit hour, between 0 and 23 18 I Two-digit hour, between 01 and 12 06 l Two-digit hour, between 1 and 12 6 M Two-digit minutes (with leading zeroes) 05 S Two-digit seconds (with leading zeroes) 19 L Three-digit milliseconds (with leading zeroes) 047 N Nine-digit nanoseconds (with leading zeroes) 047000000 P Uppercase morning or afternoon marker PM p Lowercase morning or afternoon marker pm z RFC 822 numeric offset from GMT -0800 Z Time zone PST s Seconds since 1970-01-01 00:00:00 GMT 1078884319 Q Milliseconds since 1970-01-01 00:00:00 GMT 1078884319047
  • 18.
    PARSING STRINGS INTODATES: • The SimpleDateFormat class has some additional methods, notably parse( ) , which tries to parse a string according to the format stored in the given SimpleDateFormat object. For example: import java.util.*; import java.text.*; public class DateDemo { public static void main(String args[]) { SimpleDateFormat ft = new SimpleDateFormat ("yyyy-MM-dd"); String sdate="2013-03-08"; Date t= ft.parse(sdate); System.out.println(t); } } This would produce following result: Fri Mar 08 00:00:00 PST 2013
  • 19.
    SLEEPING FOR AWHILE: • You can sleep for any period of time from one millisecond up to the lifetime of your computer. For example, following program would sleep for 5 seconds: import java.util.*; import java.text.*; public class DateDemo { public static void main(String args[])throws Exception { System.out.println(new Date( ) + ""); Thread.sleep(5000); System.out.println(new Date( ) + ""); } } This would produce following result: Mon Mar 04 00:32:29 PST 2013 Mon Mar 04 00:32:34 PST 2013
  • 20.
    MEASURING ELAPSED TIME: • Sometime you may need to measure point in time in milliseconds. So let's re-write above example once again: import java.util.*; import java.text.*; public class DateDemo { public static void main(String args[])throws Exception { long start = System.currentTimeMillis( ); System.out.println(new Date( ) + ""); Thread.sleep(5000); System.out.println(new Date( ) + ""); long end = System.currentTimeMillis( ); long diff = end - start; System.out.println("Difference is : " + diff); } } This would produce following result: Mon Mar 04 00:37:43 PST 2013 Mon Mar 04 00:37:48 PST 2013 Difference is : 5054
  • 21.
    THE CALENDAR CLASS • The Calendar class is an abstract class that provides methods for converting between a specific instant in time and a set of calendar fields such as YEAR, MONTH, DAY_OF_MONTH, HOUR, and so on, and for manipulating the calendar fields, such as getting the date of the next week. An instant in time can be represented by a millisecond value that is an offset from the Epoch, January 1, 1970 00:00:00.000 GMT (Gregorian). • The class also provides additional fields and methods for implementing a concrete calendar system outside the package. Those fields and methods are defined as protected. • Like other locale-sensitive classes, Calendar provides a class method, getInstance, for getting a generally useful object of this type. Calendar's getInstance method returns a Calendar object whose calendar fields have been initialized with the current date and time: • Calendar rightNow = Calendar.getInstance();
  • 22.
    CALENDAR CLASS FIELDS static intAM_PM           Field number for get and set indicating whether the HOUR is before or after noon. static int APRIL Value of the MONTH field indicating the fourth month of the year in the Gregorian and Julian calendars. static int AUGUST Value of the MONTH field indicating the eighth month of the year in the Gregorian and Julian calendars. static int DATE Field number for get and set indicating the day of the month. static int DAY_OF_MONTH Field number for get and set indicating the day of the month. static int DAY_OF_WEEK Field number for get and set indicating the day of the week. static int DAY_OF_WEEK_IN_MONTH Field number for get and set indicating the ordinal number of the day of the week within the current month. static int DAY_OF_YEAR Field number for get and set indicating the day number within the current year. static int DECEMBER Value of the MONTH field indicating the twelfth month of the year in the Gregorian and Julian calendars. static int ERA Field number for get and set indicating the era, e.g., AD or BC in the Julian calendar. static int FEBRUARY Value of the MONTH field indicating the second month of the year in the Gregorian and Julian calendars.
  • 23.
    static int FRIDAY           Value of the DAY_OF_WEEK field indicating Friday. static int HOUR Field number for get and set indicating the hour of the morning or afternoon. static int HOUR_OF_DAY Field number for get and set indicating the hour of the day. static int JANUARY Value of the MONTH field indicating the first month of the year in the Gregorian and Julian calendars. static int JULY Value of the MONTH field indicating the seventh month of the year in the Gregorian and Julian calendars. static int JUNE Value of the MONTH field indicating the sixth month of the year in the Gregorian and Julian calendars. static int MARCH Value of the MONTH field indicating the third month of the year in the Gregorian and Julian calendars. static int MAY Value of the MONTH field indicating the fifth month of the year in the Gregorian and Julian calendars. static int MINUTE Field number for get and set indicating the minute within the hour. static int MONDAY Value of the DAY_OF_WEEK field indicating Monday.
  • 24.
    static in MONTH  t           Field number for get and set indicating the month. static in NOVEMBER t Value of the MONTH field indicating the eleventh month of the year in the Gregorian and Julian calendars. static in OCTOBER t Value of the MONTH field indicating the tenth month of the year in the Gregorian and Julian calendars. static in SATURDAY t Value of the DAY_OF_WEEK field indicating Saturday. static in SECOND t Field number for get and set indicating the second within the minute. static in SEPTEMBER t Value of the MONTH field indicating the ninth month of the year in the Gregorian and Julian calendars. static in SUNDAY t Value of the DAY_OF_WEEK field indicating Sunday. static in THURSDAY t Value of the DAY_OF_WEEK field indicating Thursday. static in TUESDAY t Value of the DAY_OF_WEEK field indicating Tuesday. static in WEDNESDAY t Value of the DAY_OF_WEEK field indicating Wednesday. static in WEEK_OF_MONTH t Field number for get and set indicating the week number within the current month. static in WEEK_OF_YEAR t Field number for get and set indicating the week number within the current year. static in YEAR t Field number for get and set indicating the year.
  • 25.
    CALENDAR CLASS METHODS MethodSummary abstract  void add(int field, int amount) Adds or subtracts the specified amount of time to the given calendar field, based on the calendar's rules.  boolean after(Object when) Returns whether this Calendar represents a time after the time represented by the specified Object.  boolean before(Object when) Returns whether this Calendar represents a time before the time represented by the specified Object.  int compareTo(Calendar anotherCalendar) Compares the time values (millisecond offsets from the Epoch) represented by two Calendar objects.  boolean equals(Object obj) Compares this Calendar to the specified Object.  int get(int field) Returns the value of the given calendar field. static Calendar getInstance() Gets a calendar using the default time zone and locale.  Date getTime() Returns a Date object representing this Calendar's time value (millisecond offset from the Epoch).  long getTimeInMillis() Returns this Calendar's time value in milliseconds.  void roll(int field, int amount) Adds the specified (signed) amount to the specified calendar field without changing larger fields.  void set(int field, int value) Sets the given calendar field to the given value.  void set(int year, int month, int date) Sets the values for the calendar fields YEAR, MONTH, and DAY_OF_MONTH.
  • 26.
    THE CALENDAR CLASS • Getting the value of the fields • The following field names can be used as an argument to the Calendar.get() method. • Access Method Meaning • calob.get(Calendar.YEAR) int value of the year • calob.get(Calendar.MONTH) int value of the month (0-11) • calob.get(Calendar.DAY_OF_MONTH) int value of the day of the month (1-31) • calob.get(Calendar.DAY_OF_WEEK) int value of the day of the week (0-6) • calob.get(Calendar.HOUR) int value of the hour in 12 hour notation (0-12) • calob.get(Calendar.AM_PM) returns either Calendar.AM or Calendar.PM • calob.get(Calendar.HOUR_OF_DAY) int value of the hour of the day in 24-hour notation (0-24) • calob.get(Calendar.MINUTE) int value of the minute in the hour (0-59) • calob.get(Calendar.SECOND) int value of the second within the minute (0-59). • calob.get(Calendar.MILLISECOND) int value of the milliseconds within a second (0-999).
  • 27.
    Code Snippet for getting calendar fields. import java.util.*; import java.text.*; public class DateDemo { public static void main(String args[])throws Exception { Calendar cal = Calendar.getInstance(); // You cannot use Date class to extract individual Date fields int year = cal.get(Calendar.YEAR); int month = cal.get(Calendar.MONTH); // 0 to 11 int day = cal.get(Calendar.DAY_OF_MONTH); int hour = cal.get(Calendar.HOUR_OF_DAY); int minute = cal.get(Calendar.MINUTE); int second = cal.get(Calendar.SECOND); System.out.printf("Now is %d/%d/%d %d:%d:%dn", year,month+1, day, hour, minute, second); } } This would produce following result: Now is 2013/3/5 0:39:48
  • 28.
    THE CALENDAR CLASS • Setting the value of the fields • The following field names can be used as an argument to the Calendar.set() method. • Access Method Meaning • calob.set(Calendar.YEAR,2013) int value of the year • calob.set(Calendar.MONTH,1) int value of the month (0-11) • calob.set(Calendar.DAY_OF_MONTH,1) int value of the day of the month (1-31) • calob.set(Calendar.DAY_OF_WEEK,1) int value of the day of the week (0-6) • calob.set(Calendar.HOUR,1) int value of the hour in 12 hour notation (0-12) • calob.set(Calendar.AM_PM,1) returns either Calendar.AM or Calendar.PM • calob.set(Calendar.HOUR_OF_DAY,1) int value of the hour of the day in 24-hour notation (0-24) • calob.set(Calendar.MINUTE,1) int value of the minute in the hour (0-59) • calob.set(Calendar.SECOND,1) int value of the second within the minute (0-59). • calob.set(Calendar.MILLISECOND,1) int value of the milliseconds within a second (0-999). • OR • Calob.set(2013, 3, 10) int year ,month,day
  • 29.
    Code Snippet for setting calendar fields. import java.util.*; import java.text.*; public class DateDemo { public static void main(String args[])throws Exception { Calendar cal = Calendar.getInstance(); // You cannot use Date class to extract individual Date fields cal.set(Calendar.YEAR,2014); cal.set(Calendar.MONTH,4); // 0 to 11 cal.set(Calendar.DAY_OF_MONTH,5); cal.set(Calendar.HOUR_OF_DAY,7); cal.set(Calendar.MINUTE,3); cal.set(Calendar.SECOND,7); System.out.println(cal.getTime()); cal.set(2010,1,1); System.out.println(cal.getTime()); } } This would produce following result: Mon May 05 07:03:07 PDT 2014 Mon Feb 01 07:03:07 PST 2010
  • 30.
    THE CALENDAR CLASS • Adding the value of the fields • The following field names can be used as an argument to the Calendar.add() method. • Access Method Meaning • calob.add(Calendar.YEAR,1) int value of the year • calob.add(Calendar.MONTH,1) int value of the month (0-11) • calob.add(Calendar.DAY_OF_MONTH,1) int value of the day of the month (1-31) • calob.add(Calendar.DAY_OF_WEEK,1) int value of the day of the week (0-6) • calob.add(Calendar.HOUR,1) int value of the hour in 12 hour notation (0-12) • calob.add(Calendar.AM_PM,1) returns either Calendar.AM or Calendar.PM • calob.add(Calendar.HOUR_OF_DAY,1) int value of the hour of the day in 24-hour notation (0-24) • calob.add(Calendar.MINUTE,1) int value of the minute in the hour (0-59) • calob.add(Calendar.SECOND,1) int value of the second within the minute (0-59). • calob.add(Calendar.MILLISECOND,1) int value of the milliseconds within a second (0-999).
  • 31.
    Code Snippet for adding calendar fields. import java.util.*; import java.text.*; public class DateDemo { public static void main(String args[])throws Exception { Calendar cal = Calendar.getInstance(); // You cannot use Date class to extract individual Date fields cal.add(Calendar.YEAR,2); cal.add(Calendar.MONTH,4); // 0 to 11 cal.add(Calendar.DAY_OF_MONTH,5); cal.add(Calendar.HOUR_OF_DAY,7); cal.add(Calendar.MINUTE,3); cal.add(Calendar.SECOND,7); System.out.println(cal.getTime()); } } This would produce following result: Fri Jul 10 07:53:29 PDT 2015
  • 32.
    THE CALENDAR CLASS • Substrating the value of the fields • The following field names can be used as an argument to the Calendar.add() method. • Access Method Meaning • calob.add(Calendar.YEAR,-1) int value of the year • calob.add(Calendar.MONTH,-1) int value of the month (0-11) • calob.add(Calendar.DAY_OF_MONTH,-1) int value of the day of the month (1-31) • calob.add(Calendar.DAY_OF_WEEK,-1) int value of the day of the week (0-6) • calob.add(Calendar.HOUR,-1) int value of the hour in 12 hour notation (0-12) • calob.add(Calendar.AM_PM,-1) returns either Calendar.AM or Calendar.PM • calob.add(Calendar.HOUR_OF_DAY,-1) int value of the hour of the day in 24-hour notation (0-24) • calob.add(Calendar.MINUTE,-1) int value of the minute in the hour (0-59) • calob.add(Calendar.SECOND,-1) int value of the second within the minute (0-59). • calob.add(Calendar.MILLISECOND,-1) int value of the milliseconds within a second (0-999).
  • 33.
    Code Snippet for substrating calendar fields. import java.util.*; import java.text.*; public class DateDemo { public static void main(String args[])throws Exception { Calendar cal = Calendar.getInstance(); // You cannot use Date class to extract individual Date fields cal.add(Calendar.YEAR,-2); cal.add(Calendar.MONTH,-4); // 0 to 11 cal.add(Calendar.DAY_OF_MONTH,-5); cal.add(Calendar.HOUR_OF_DAY,-7); cal.add(Calendar.MINUTE,-3); cal.add(Calendar.SECOND,-7); System.out.println(cal.getTime()); } } This would produce following result: Sat Oct 30 17:49:57 PDT 2010
  • 34.
    GREGORIANCALENDAR CLASS: • GregorianCalendar is a concrete implementation of a Calendar class that implements the normal Gregorian calendar with which you are familiar. I did not discuss Calender class in this slid, you can look standard Java documentation for this. • The getInstance( ) method of Calendar returns a GregorianCalendar initialized with the current date and time in the default locale and time zone. GregorianCalendar defines two fields: AD and BC. These represent the two eras defined by the Gregorian calendar.
  • 35.
    CONSTRUCTORS FOR GREGORIANCALENDAR • There are also several constructors for GregorianCalendar objects: GregorianCalendar() Constructs a default GregorianCalendar using the current time in the default time zone with the default locale. GregorianCalendar(int year, int month, int date) Constructs a GregorianCalendar with the given date set in the default time zone with the default locale. GregorianCalendar(int year, int month, int date, int hour, int minute) Constructs a GregorianCalendar with the given date and time set for the default time zone with the default locale. GregorianCalendar(int year, int month, int date, int hour, int minute, int second) Constructs a GregorianCalendar with the given date and time set for the default time zone with the default locale.
  • 36.
    EXERCISES  Write aprogram that takes your Date of Birth, and prints exact years, months, days hours, minutes and seconds upto current date.  Write a program which sets the Expiry date, if current date is Expiry date then terminate your program.  Write a program to create a digital clock.

Editor's Notes

  • #3 * 03/07/13 07/16/96 (c) 2005 National Academy for Software Development - http://academy.devbg.org. All rights reserved. Unauthorized copying or re-distribution is strictly prohibited.* ##
  • #4 * 03/07/13 07/16/96 (c) 2005 National Academy for Software Development - http://academy.devbg.org. All rights reserved. Unauthorized copying or re-distribution is strictly prohibited.* ##
  • #5 * 03/07/13 07/16/96 (c) 2005 National Academy for Software Development - http://academy.devbg.org. All rights reserved. Unauthorized copying or re-distribution is strictly prohibited.* ##
  • #6 * 03/07/13 07/16/96 (c) 2005 National Academy for Software Development - http://academy.devbg.org. All rights reserved. Unauthorized copying or re-distribution is strictly prohibited.* ##
  • #12 * 03/07/13 07/16/96 (c) 2005 National Academy for Software Development - http://academy.devbg.org. All rights reserved. Unauthorized copying or re-distribution is strictly prohibited.* ##
  • #25 * 03/07/13 07/16/96 (c) 2005 National Academy for Software Development - http://academy.devbg.org. All rights reserved. Unauthorized copying or re-distribution is strictly prohibited.* ##
  • #37 * 03/07/13 07/16/96 (c) 2005 National Academy for Software Development - http://academy.devbg.org. All rights reserved. Unauthorized copying or re-distribution is strictly prohibited.* ##