Date and time manipulation

36

description

 

Transcript of Date and time manipulation

Page 1: Date and time manipulation
Page 2: Date and time manipulation

DATE AND TIME MANIPULATION

Page 3: Date and time manipulation

CONTENTS1. Overview

2. Understanding Date Class

• Declaring, Creating, getting and Printing dates and time

3. Date and Time operations

• Comparing dates

4. Formating Dates

• Printing dates according to required format

Page 4: Date and time manipulation

CONTENTS5. Understanding Calendar Class

• Declaring, Creating, getting,setting and Printing Calendar objects

6. Calendar Operations

• Extracting,adding and rolling the Calendar fields

7. Undarstanding GregoreanCalendar

Page 5: Date and time manipulation

WORKING WITH DATE CLASS

Page 6: Date and time manipulation

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 )

Page 7: Date and time manipulation

DATE CLASS METHODS• Once you have a Date object available, you can call any of the following support methods to

play with dates:

Page 8: Date and time manipulation

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);

} }

Mon Mar 04 00:04:41 PST 2013

This would produce following result:

Page 9: Date and time manipulation

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.

Page 10: Date and time manipulation

COMPARING DATESimport 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));

} }

truefalsefalse0

This would produce following result:

Page 11: Date and time manipulation

FORMATING DATES

Page 12: Date and time manipulation

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)); }}

Current Date: Mon 2013.03.04 at 12:05:35 AM PST

This would produce following result:

Page 13: Date and time manipulation

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 ExampleG Era designator ADy Year in four digits 2001M Month in year July or 07d Day in month 10h Hour in A.M./P.M. (1~12) 12H Hour in day (0~23) 22m Minute in hour 30s Second in minute 55S Millisecond 234E Day in week TuesdayD Day in year 360F Day of week in month 2 (second Wed. in July)w Week in year 40W Week in month 1a A.M./P.M. marker PMk Hour in day (1~24) 24K Hour in A.M./P.M. (0~11) 10z Time zone Eastern Standard Time' Escape for text Delimiter" Single quote `

Page 14: Date and time manipulation

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); }}

Current Date/Time : Mon Mar 04 00:06:20 PST 2013

This would produce following result:

Page 15: Date and time manipulation

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); }}

Due date: March 04, 2013

This would produce following result:

Page 16: Date and time manipulation

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); }}

Due date: March 4, 2013

This would produce following result:

Page 17: Date and time manipulation

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 Examplec Complete date and time Mon May 04 09:51:52 CDT 2009F ISO 8601 date 2004-02-09D U.S. formatted date (month/day/year) 02/09/2004T 24-hour time 18:05:19r 12-hour time 06:05:19 pmR 24-hour time, no seconds 18:05Y Four-digit year (with leading zeroes) 2004y Last two digits of the year (with leading zeroes) 04C First two digits of the year (with leading zeroes) 20B Full month name Februaryb Abbreviated month name Febn Two-digit month (with leading zeroes) 02d Two-digit day (with leading zeroes) 03e Two-digit day (without leading zeroes) 9A Full weekday name Mondaya Abbreviated weekday name Monj Three-digit day of year (with leading zeroes) 069H Two-digit hour, between 00 and 23 18k Two-digit hour, between 0 and 23 18I Two-digit hour, between 01 and 12 06l Two-digit hour, between 1 and 12 6M Two-digit minutes (with leading zeroes) 05S Two-digit seconds (with leading zeroes) 19L Three-digit milliseconds (with leading zeroes) 047N Nine-digit nanoseconds (with leading zeroes) 047000000P Uppercase morning or afternoon marker PMp Lowercase morning or afternoon marker pmz RFC 822 numeric offset from GMT -0800Z Time zone PSTs Seconds since 1970-01-01 00:00:00 GMT 1078884319Q Milliseconds since 1970-01-01 00:00:00 GMT 1078884319047

Page 18: Date and time manipulation

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);

}}

Fri Mar 08 00:00:00 PST 2013

This would produce following result:

Page 19: Date and time manipulation

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( ) + ""); }}

Mon Mar 04 00:32:29 PST 2013Mon Mar 04 00:32:34 PST 2013

This would produce following result:

Page 20: Date and time manipulation

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); }}

Mon Mar 04 00:37:43 PST 2013Mon Mar 04 00:37:48 PST 2013Difference is : 5054

This would produce following result:

Page 21: Date and time manipulation

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();

Page 22: Date and time manipulation

CALENDAR CLASS FIELDSstatic 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.

Page 23: Date and time manipulation

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 intMARCH Value of the MONTH field indicating the third month of the year in the Gregorian and Julian calendars.

static intMAY Value of the MONTH field indicating the fifth month of the year in the Gregorian and Julian calendars.

static intMINUTE Field number for get and set indicating the minute within the hour.

static intMONDAY Value of the DAY_OF_WEEK field indicating Monday.

Page 24: Date and time manipulation

static int MONTH           Field number for get and set indicating the month.

static int NOVEMBER Value of the MONTH field indicating the eleventh month of the year in the Gregorian and Julian calendars.

static intOCTOBER Value of the MONTH field indicating the tenth month of the year in the Gregorian and Julian calendars.

static int SATURDAY Value of the DAY_OF_WEEK field indicating Saturday.

static int SECOND Field number for get and set indicating the second within the minute.

static int SEPTEMBER Value of the MONTH field indicating the ninth month of the year in the Gregorian and Julian calendars.

static int SUNDAY Value of the DAY_OF_WEEK field indicating Sunday.

static int THURSDAY Value of the DAY_OF_WEEK field indicating Thursday.

static int TUESDAY Value of the DAY_OF_WEEK field indicating Tuesday.

static intWEDNESDAY Value of the DAY_OF_WEEK field indicating Wednesday.

static intWEEK_OF_MONTH Field number for get and set indicating the week number within the current month.

static intWEEK_OF_YEAR Field number for get and set indicating the week number within the current year.

static int YEAR Field number for get and set indicating the year.

Page 25: Date and time manipulation

CALENDAR CLASS METHODSMethod 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.

Page 26: Date and time manipulation

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).

Page 27: Date and time manipulation

• 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:%d\n",

year,month+1, day, hour, minute, second);}}

Now is 2013/3/5 0:39:48

This would produce following result:

Page 28: Date and time manipulation

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

Page 29: Date and time manipulation

• 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()); }}

Mon May 05 07:03:07 PDT 2014Mon Feb 01 07:03:07 PST 2010

This would produce following result:

Page 30: Date and time manipulation

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).

Page 31: Date and time manipulation

• 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());

}}

Fri Jul 10 07:53:29 PDT 2015

This would produce following result:

Page 32: Date and time manipulation

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).

Page 33: Date and time manipulation

• 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());

}}

Sat Oct 30 17:49:57 PDT 2010

This would produce following result:

Page 34: Date and time manipulation

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.

Page 35: Date and time manipulation

CONSTRUCTORS FOR GREGORIANCALENDAR• There are also several constructors for GregorianCalendar objects:

GregorianCalendar()

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

GregorianCalendar(int year, int month, int date)

Constructs a GregorianCalendar with the given date set in the defaulttime 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 defaulttime 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 defaulttime zone with the default locale.

Page 36: Date and time manipulation

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.