SlideShare une entreprise Scribd logo
1  sur  36
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.

Contenu connexe

Tendances

Tendances (17)

lecture 4
lecture 4lecture 4
lecture 4
 
Lec8
Lec8Lec8
Lec8
 
Origin of Universe (Twin)
Origin of Universe (Twin)Origin of Universe (Twin)
Origin of Universe (Twin)
 
Aaex5 group2(中英夾雜)
Aaex5 group2(中英夾雜)Aaex5 group2(中英夾雜)
Aaex5 group2(中英夾雜)
 
Discretization
DiscretizationDiscretization
Discretization
 
Rand final
Rand finalRand final
Rand final
 
A Note on TopicRNN
A Note on TopicRNNA Note on TopicRNN
A Note on TopicRNN
 
Dsp lecture vol 2 dft & fft
Dsp lecture vol 2 dft & fftDsp lecture vol 2 dft & fft
Dsp lecture vol 2 dft & fft
 
How to work with dates and times in swift 3
How to work with dates and times in swift 3How to work with dates and times in swift 3
How to work with dates and times in swift 3
 
Chapter 9 computation of the dft
Chapter 9 computation of the dftChapter 9 computation of the dft
Chapter 9 computation of the dft
 
Lec9
Lec9Lec9
Lec9
 
A Note on Latent LSTM Allocation
A Note on Latent LSTM AllocationA Note on Latent LSTM Allocation
A Note on Latent LSTM Allocation
 
Signals Processing Assignment Help
Signals Processing Assignment HelpSignals Processing Assignment Help
Signals Processing Assignment Help
 
Decimation in time and frequency
Decimation in time and frequencyDecimation in time and frequency
Decimation in time and frequency
 
The Ring programming language version 1.9 book - Part 30 of 210
The Ring programming language version 1.9 book - Part 30 of 210The Ring programming language version 1.9 book - Part 30 of 210
The Ring programming language version 1.9 book - Part 30 of 210
 
The Ring programming language version 1.5.3 book - Part 23 of 184
The Ring programming language version 1.5.3 book - Part 23 of 184The Ring programming language version 1.5.3 book - Part 23 of 184
The Ring programming language version 1.5.3 book - Part 23 of 184
 
Sns mid term-test2-solution
Sns mid term-test2-solutionSns mid term-test2-solution
Sns mid term-test2-solution
 

En vedette

Date and Time MomentJS Edition
Date and Time MomentJS EditionDate and Time MomentJS Edition
Date and Time MomentJS EditionMaggie Pint
 
Media pembelajaran.ppt.bhs inggris sd
Media pembelajaran.ppt.bhs inggris sdMedia pembelajaran.ppt.bhs inggris sd
Media pembelajaran.ppt.bhs inggris sddry1
 
Using End-Of-Time Date Semantics to Improve Performance
Using End-Of-Time Date Semantics to Improve PerformanceUsing End-Of-Time Date Semantics to Improve Performance
Using End-Of-Time Date Semantics to Improve PerformanceDonald Bales
 
Telling the time
Telling the timeTelling the time
Telling the timeNeus Puig
 
Telling the time, tell the time esl efl
Telling the time, tell the time esl eflTelling the time, tell the time esl efl
Telling the time, tell the time esl eflIrenya S
 
Time management ppt
Time management pptTime management ppt
Time management pptUzma Batool
 

En vedette (11)

Ruby Time & Date
Ruby Time & DateRuby Time & Date
Ruby Time & Date
 
Biodiversidad
BiodiversidadBiodiversidad
Biodiversidad
 
Date and Time MomentJS Edition
Date and Time MomentJS EditionDate and Time MomentJS Edition
Date and Time MomentJS Edition
 
Media pembelajaran.ppt.bhs inggris sd
Media pembelajaran.ppt.bhs inggris sdMedia pembelajaran.ppt.bhs inggris sd
Media pembelajaran.ppt.bhs inggris sd
 
Functional text all
Functional text allFunctional text all
Functional text all
 
Adjectives - Their Types
Adjectives - Their TypesAdjectives - Their Types
Adjectives - Their Types
 
Using End-Of-Time Date Semantics to Improve Performance
Using End-Of-Time Date Semantics to Improve PerformanceUsing End-Of-Time Date Semantics to Improve Performance
Using End-Of-Time Date Semantics to Improve Performance
 
Telling the time
Telling the timeTelling the time
Telling the time
 
Telling the time ppt
Telling the time pptTelling the time ppt
Telling the time ppt
 
Telling the time, tell the time esl efl
Telling the time, tell the time esl eflTelling the time, tell the time esl efl
Telling the time, tell the time esl efl
 
Time management ppt
Time management pptTime management ppt
Time management ppt
 

Similaire à Date and time manipulation

Brand New Date and Time API
Brand New Date and Time APIBrand New Date and Time API
Brand New Date and Time APIKenji HASUNUMA
 
Brand new Date and Time API
Brand new Date and Time APIBrand new Date and Time API
Brand new Date and Time APIKenji HASUNUMA
 
Php date &amp; time functions
Php date &amp; time functionsPhp date &amp; time functions
Php date &amp; time functionsProgrammer Blog
 
Introduction to Date and Time API 4
Introduction to Date and Time API 4Introduction to Date and Time API 4
Introduction to Date and Time API 4Kenji HASUNUMA
 
Data Wrangling: Working with Date / Time Data and Visualizing It
Data Wrangling: Working with Date / Time Data and Visualizing ItData Wrangling: Working with Date / Time Data and Visualizing It
Data Wrangling: Working with Date / Time Data and Visualizing Itkanaugust
 
Introduction to Date and Time API 4
Introduction to Date and Time API 4Introduction to Date and Time API 4
Introduction to Date and Time API 4Kenji HASUNUMA
 
C# Tutorial MSM_Murach chapter-09-slides
C# Tutorial MSM_Murach chapter-09-slidesC# Tutorial MSM_Murach chapter-09-slides
C# Tutorial MSM_Murach chapter-09-slidesSami Mut
 
Introduction to Date and Time API 3
Introduction to Date and Time API 3Introduction to Date and Time API 3
Introduction to Date and Time API 3Kenji HASUNUMA
 
Dates and Times in Java 7 and Java 8
Dates and Times in Java 7 and Java 8Dates and Times in Java 7 and Java 8
Dates and Times in Java 7 and Java 8Fulvio Corno
 
JSR 310. New Date API in Java 8
JSR 310. New Date API in Java 8JSR 310. New Date API in Java 8
JSR 310. New Date API in Java 8Serhii Kartashov
 
Introduction to Date and Time API 3
Introduction to Date and Time API 3Introduction to Date and Time API 3
Introduction to Date and Time API 3Kenji HASUNUMA
 
Java 8 Date and Time API
Java 8 Date and Time APIJava 8 Date and Time API
Java 8 Date and Time APISualeh Fatehi
 
Datetime - Julian Date
Datetime - Julian DateDatetime - Julian Date
Datetime - Julian DateShuo Chen
 
SessionSeven_WorkingWithDatesandTime
SessionSeven_WorkingWithDatesandTimeSessionSeven_WorkingWithDatesandTime
SessionSeven_WorkingWithDatesandTimeHellen Gakuruh
 

Similaire à Date and time manipulation (20)

17 ruby date time
17 ruby date time17 ruby date time
17 ruby date time
 
Brand New Date and Time API
Brand New Date and Time APIBrand New Date and Time API
Brand New Date and Time API
 
Brand new Date and Time API
Brand new Date and Time APIBrand new Date and Time API
Brand new Date and Time API
 
Php date &amp; time functions
Php date &amp; time functionsPhp date &amp; time functions
Php date &amp; time functions
 
jkfdlsajfklafj
jkfdlsajfklafjjkfdlsajfklafj
jkfdlsajfklafj
 
doc
docdoc
doc
 
Introduction to Date and Time API 4
Introduction to Date and Time API 4Introduction to Date and Time API 4
Introduction to Date and Time API 4
 
Data Wrangling: Working with Date / Time Data and Visualizing It
Data Wrangling: Working with Date / Time Data and Visualizing ItData Wrangling: Working with Date / Time Data and Visualizing It
Data Wrangling: Working with Date / Time Data and Visualizing It
 
Java Day-7
Java Day-7Java Day-7
Java Day-7
 
Introduction to Date and Time API 4
Introduction to Date and Time API 4Introduction to Date and Time API 4
Introduction to Date and Time API 4
 
C# Tutorial MSM_Murach chapter-09-slides
C# Tutorial MSM_Murach chapter-09-slidesC# Tutorial MSM_Murach chapter-09-slides
C# Tutorial MSM_Murach chapter-09-slides
 
Introduction to Date and Time API 3
Introduction to Date and Time API 3Introduction to Date and Time API 3
Introduction to Date and Time API 3
 
Dates and Times in Java 7 and Java 8
Dates and Times in Java 7 and Java 8Dates and Times in Java 7 and Java 8
Dates and Times in Java 7 and Java 8
 
Python time
Python timePython time
Python time
 
JSR 310. New Date API in Java 8
JSR 310. New Date API in Java 8JSR 310. New Date API in Java 8
JSR 310. New Date API in Java 8
 
Introduction to Date and Time API 3
Introduction to Date and Time API 3Introduction to Date and Time API 3
Introduction to Date and Time API 3
 
Java 8 Date and Time API
Java 8 Date and Time APIJava 8 Date and Time API
Java 8 Date and Time API
 
Datetime - Julian Date
Datetime - Julian DateDatetime - Julian Date
Datetime - Julian Date
 
SessionSeven_WorkingWithDatesandTime
SessionSeven_WorkingWithDatesandTimeSessionSeven_WorkingWithDatesandTime
SessionSeven_WorkingWithDatesandTime
 
Java 8 Date and Time API
Java 8 Date and Time APIJava 8 Date and Time API
Java 8 Date and Time API
 

Dernier

Unit-IV; Professional Sales Representative (PSR).pptx
Unit-IV; Professional Sales Representative (PSR).pptxUnit-IV; Professional Sales Representative (PSR).pptx
Unit-IV; Professional Sales Representative (PSR).pptxVishalSingh1417
 
How to Manage Global Discount in Odoo 17 POS
How to Manage Global Discount in Odoo 17 POSHow to Manage Global Discount in Odoo 17 POS
How to Manage Global Discount in Odoo 17 POSCeline George
 
How to Create and Manage Wizard in Odoo 17
How to Create and Manage Wizard in Odoo 17How to Create and Manage Wizard in Odoo 17
How to Create and Manage Wizard in Odoo 17Celine George
 
Explore beautiful and ugly buildings. Mathematics helps us create beautiful d...
Explore beautiful and ugly buildings. Mathematics helps us create beautiful d...Explore beautiful and ugly buildings. Mathematics helps us create beautiful d...
Explore beautiful and ugly buildings. Mathematics helps us create beautiful d...christianmathematics
 
SOC 101 Demonstration of Learning Presentation
SOC 101 Demonstration of Learning PresentationSOC 101 Demonstration of Learning Presentation
SOC 101 Demonstration of Learning Presentationcamerronhm
 
1029 - Danh muc Sach Giao Khoa 10 . pdf
1029 -  Danh muc Sach Giao Khoa 10 . pdf1029 -  Danh muc Sach Giao Khoa 10 . pdf
1029 - Danh muc Sach Giao Khoa 10 . pdfQucHHunhnh
 
This PowerPoint helps students to consider the concept of infinity.
This PowerPoint helps students to consider the concept of infinity.This PowerPoint helps students to consider the concept of infinity.
This PowerPoint helps students to consider the concept of infinity.christianmathematics
 
TỔNG ÔN TẬP THI VÀO LỚP 10 MÔN TIẾNG ANH NĂM HỌC 2023 - 2024 CÓ ĐÁP ÁN (NGỮ Â...
TỔNG ÔN TẬP THI VÀO LỚP 10 MÔN TIẾNG ANH NĂM HỌC 2023 - 2024 CÓ ĐÁP ÁN (NGỮ Â...TỔNG ÔN TẬP THI VÀO LỚP 10 MÔN TIẾNG ANH NĂM HỌC 2023 - 2024 CÓ ĐÁP ÁN (NGỮ Â...
TỔNG ÔN TẬP THI VÀO LỚP 10 MÔN TIẾNG ANH NĂM HỌC 2023 - 2024 CÓ ĐÁP ÁN (NGỮ Â...Nguyen Thanh Tu Collection
 
UGC NET Paper 1 Mathematical Reasoning & Aptitude.pdf
UGC NET Paper 1 Mathematical Reasoning & Aptitude.pdfUGC NET Paper 1 Mathematical Reasoning & Aptitude.pdf
UGC NET Paper 1 Mathematical Reasoning & Aptitude.pdfNirmal Dwivedi
 
Holdier Curriculum Vitae (April 2024).pdf
Holdier Curriculum Vitae (April 2024).pdfHoldier Curriculum Vitae (April 2024).pdf
Holdier Curriculum Vitae (April 2024).pdfagholdier
 
ComPTIA Overview | Comptia Security+ Book SY0-701
ComPTIA Overview | Comptia Security+ Book SY0-701ComPTIA Overview | Comptia Security+ Book SY0-701
ComPTIA Overview | Comptia Security+ Book SY0-701bronxfugly43
 
Kodo Millet PPT made by Ghanshyam bairwa college of Agriculture kumher bhara...
Kodo Millet  PPT made by Ghanshyam bairwa college of Agriculture kumher bhara...Kodo Millet  PPT made by Ghanshyam bairwa college of Agriculture kumher bhara...
Kodo Millet PPT made by Ghanshyam bairwa college of Agriculture kumher bhara...pradhanghanshyam7136
 
Accessible Digital Futures project (20/03/2024)
Accessible Digital Futures project (20/03/2024)Accessible Digital Futures project (20/03/2024)
Accessible Digital Futures project (20/03/2024)Jisc
 
ICT Role in 21st Century Education & its Challenges.pptx
ICT Role in 21st Century Education & its Challenges.pptxICT Role in 21st Century Education & its Challenges.pptx
ICT Role in 21st Century Education & its Challenges.pptxAreebaZafar22
 
Unit-V; Pricing (Pharma Marketing Management).pptx
Unit-V; Pricing (Pharma Marketing Management).pptxUnit-V; Pricing (Pharma Marketing Management).pptx
Unit-V; Pricing (Pharma Marketing Management).pptxVishalSingh1417
 
Basic Civil Engineering first year Notes- Chapter 4 Building.pptx
Basic Civil Engineering first year Notes- Chapter 4 Building.pptxBasic Civil Engineering first year Notes- Chapter 4 Building.pptx
Basic Civil Engineering first year Notes- Chapter 4 Building.pptxDenish Jangid
 
HMCS Max Bernays Pre-Deployment Brief (May 2024).pptx
HMCS Max Bernays Pre-Deployment Brief (May 2024).pptxHMCS Max Bernays Pre-Deployment Brief (May 2024).pptx
HMCS Max Bernays Pre-Deployment Brief (May 2024).pptxEsquimalt MFRC
 
Unit-IV- Pharma. Marketing Channels.pptx
Unit-IV- Pharma. Marketing Channels.pptxUnit-IV- Pharma. Marketing Channels.pptx
Unit-IV- Pharma. Marketing Channels.pptxVishalSingh1417
 
Sociology 101 Demonstration of Learning Exhibit
Sociology 101 Demonstration of Learning ExhibitSociology 101 Demonstration of Learning Exhibit
Sociology 101 Demonstration of Learning Exhibitjbellavia9
 

Dernier (20)

Unit-IV; Professional Sales Representative (PSR).pptx
Unit-IV; Professional Sales Representative (PSR).pptxUnit-IV; Professional Sales Representative (PSR).pptx
Unit-IV; Professional Sales Representative (PSR).pptx
 
How to Manage Global Discount in Odoo 17 POS
How to Manage Global Discount in Odoo 17 POSHow to Manage Global Discount in Odoo 17 POS
How to Manage Global Discount in Odoo 17 POS
 
How to Create and Manage Wizard in Odoo 17
How to Create and Manage Wizard in Odoo 17How to Create and Manage Wizard in Odoo 17
How to Create and Manage Wizard in Odoo 17
 
Explore beautiful and ugly buildings. Mathematics helps us create beautiful d...
Explore beautiful and ugly buildings. Mathematics helps us create beautiful d...Explore beautiful and ugly buildings. Mathematics helps us create beautiful d...
Explore beautiful and ugly buildings. Mathematics helps us create beautiful d...
 
SOC 101 Demonstration of Learning Presentation
SOC 101 Demonstration of Learning PresentationSOC 101 Demonstration of Learning Presentation
SOC 101 Demonstration of Learning Presentation
 
1029 - Danh muc Sach Giao Khoa 10 . pdf
1029 -  Danh muc Sach Giao Khoa 10 . pdf1029 -  Danh muc Sach Giao Khoa 10 . pdf
1029 - Danh muc Sach Giao Khoa 10 . pdf
 
This PowerPoint helps students to consider the concept of infinity.
This PowerPoint helps students to consider the concept of infinity.This PowerPoint helps students to consider the concept of infinity.
This PowerPoint helps students to consider the concept of infinity.
 
TỔNG ÔN TẬP THI VÀO LỚP 10 MÔN TIẾNG ANH NĂM HỌC 2023 - 2024 CÓ ĐÁP ÁN (NGỮ Â...
TỔNG ÔN TẬP THI VÀO LỚP 10 MÔN TIẾNG ANH NĂM HỌC 2023 - 2024 CÓ ĐÁP ÁN (NGỮ Â...TỔNG ÔN TẬP THI VÀO LỚP 10 MÔN TIẾNG ANH NĂM HỌC 2023 - 2024 CÓ ĐÁP ÁN (NGỮ Â...
TỔNG ÔN TẬP THI VÀO LỚP 10 MÔN TIẾNG ANH NĂM HỌC 2023 - 2024 CÓ ĐÁP ÁN (NGỮ Â...
 
UGC NET Paper 1 Mathematical Reasoning & Aptitude.pdf
UGC NET Paper 1 Mathematical Reasoning & Aptitude.pdfUGC NET Paper 1 Mathematical Reasoning & Aptitude.pdf
UGC NET Paper 1 Mathematical Reasoning & Aptitude.pdf
 
Holdier Curriculum Vitae (April 2024).pdf
Holdier Curriculum Vitae (April 2024).pdfHoldier Curriculum Vitae (April 2024).pdf
Holdier Curriculum Vitae (April 2024).pdf
 
ComPTIA Overview | Comptia Security+ Book SY0-701
ComPTIA Overview | Comptia Security+ Book SY0-701ComPTIA Overview | Comptia Security+ Book SY0-701
ComPTIA Overview | Comptia Security+ Book SY0-701
 
Spatium Project Simulation student brief
Spatium Project Simulation student briefSpatium Project Simulation student brief
Spatium Project Simulation student brief
 
Kodo Millet PPT made by Ghanshyam bairwa college of Agriculture kumher bhara...
Kodo Millet  PPT made by Ghanshyam bairwa college of Agriculture kumher bhara...Kodo Millet  PPT made by Ghanshyam bairwa college of Agriculture kumher bhara...
Kodo Millet PPT made by Ghanshyam bairwa college of Agriculture kumher bhara...
 
Accessible Digital Futures project (20/03/2024)
Accessible Digital Futures project (20/03/2024)Accessible Digital Futures project (20/03/2024)
Accessible Digital Futures project (20/03/2024)
 
ICT Role in 21st Century Education & its Challenges.pptx
ICT Role in 21st Century Education & its Challenges.pptxICT Role in 21st Century Education & its Challenges.pptx
ICT Role in 21st Century Education & its Challenges.pptx
 
Unit-V; Pricing (Pharma Marketing Management).pptx
Unit-V; Pricing (Pharma Marketing Management).pptxUnit-V; Pricing (Pharma Marketing Management).pptx
Unit-V; Pricing (Pharma Marketing Management).pptx
 
Basic Civil Engineering first year Notes- Chapter 4 Building.pptx
Basic Civil Engineering first year Notes- Chapter 4 Building.pptxBasic Civil Engineering first year Notes- Chapter 4 Building.pptx
Basic Civil Engineering first year Notes- Chapter 4 Building.pptx
 
HMCS Max Bernays Pre-Deployment Brief (May 2024).pptx
HMCS Max Bernays Pre-Deployment Brief (May 2024).pptxHMCS Max Bernays Pre-Deployment Brief (May 2024).pptx
HMCS Max Bernays Pre-Deployment Brief (May 2024).pptx
 
Unit-IV- Pharma. Marketing Channels.pptx
Unit-IV- Pharma. Marketing Channels.pptxUnit-IV- Pharma. Marketing Channels.pptx
Unit-IV- Pharma. Marketing Channels.pptx
 
Sociology 101 Demonstration of Learning Exhibit
Sociology 101 Demonstration of Learning ExhibitSociology 101 Demonstration of Learning Exhibit
Sociology 101 Demonstration of Learning Exhibit
 

Date and time manipulation

  • 1.
  • 2. DATE AND TIME MANIPULATION
  • 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
  • 6. 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 )
  • 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; 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
  • 12. 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
  • 13. 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 `
  • 14. 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
  • 15. 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
  • 16. 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
  • 17. 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
  • 18. 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
  • 19. 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
  • 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 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.
  • 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 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.
  • 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 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.

Notes de l'éditeur

  1. * 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.* ##
  2. * 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.* ##
  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.* ##
  7. * 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.* ##