Java - Date and TimeJava provides the Date class available in java dateandtime.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.
Date()
The following constructor accepts one argument that equals the number of milliseconds that have elapsed since midnight, January 1, 1970
Date(long millisec)
Once you have a Date object available, you can call any of the following support methods to play with dates:
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 dateandtime.util.Date;
public class DateDemo{ public static void main(String args[]){ // Instantiate a Date object Date date =newDate(); // display time and date using toString() System.out.println(date.toString()); } } This would produce the following result:
MonMay0409:51:52 CDT 2009
Date Comparison: There are following three ways to compare two dates:
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 dateandtime.util.*;
import java dateandtime.text.*; public class DateDemo{ public static void main(String args[]){ Date dNow =newDate(); SimpleDateFormat ft = newSimpleDateFormat("E yyyy.MM.dd 'at' hh:mm:ss a zzz"); System.out.println("Current Date: "+ ft.format(dNow)); } } This would produce the following result:
CurrentDate:Sun2004.07.18 at 04:14:09 PM PDT
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:
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 dateandtime.util.Date;
public class DateDemo{ public static void main(String args[]){ // Instantiate a Date object Date date =new Date(); // display time and date using toString() String str =String.format("Current Date/Time : %tc", date ); System.out.printf(str); } } This would produce the following result:
CurrentDate/Time:SatDec1516:37:57 MST 2012
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 dateandtime.util.Date;
public class DateDemo{ public static void main(String args[]){ // Instantiate a Date object Date date =new Date(); // display time and date using toString() System.out.printf("%1$s %2$tB %2$td, %2$tY", "Due date:", date); } } This would produce the following result:
Due date:February09,2004
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 dateandtime.util.Date;
public class DateDemo{ public static void main(String args[]){ // Instantiate a Date object Date date =new Date(); // display formatted date System.out.printf("%s %tB % } } This would produce the following result:
Due date:February09,2004
Date and Time Conversion Characters:
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 dateandtime.util.*;
import java dateandtime.text.*; public class DateDemo{ public static void main(String args[]){ SimpleDateFormat ft =new SimpleDateFormat("yyyy-MM-dd"); String input = args.length ==0?"1818-11-11": args[0]; System.out.print(input +" Parses as "); Date t; try{ t = ft.parse(input); System.out.println(t); }catch(ParseException e){ System.out.println("Unparseable using "+ ft); } } } A sample run of the above program would produce the following result:
$ java dateandtime DateDemo
1818-11-11ParsesasWedNov1100:00:00 GMT 1818 $ java dateandtime DateDemo2007-12-01 2007-12-01ParsesasSatDec0100:00:00 GMT 2007 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 10 seconds:
import java dateandtime.util.*;
public class SleepDemo{ public static void main(String args[]){ try{ System.out.println(new Date()+"\n"); Thread.sleep(5*60*10); System.out.println(new Date()+"\n"); }catch(Exception e){ System.out.println("Got an exception!"); } } } This would produce the following result:
SunMay0318:04:41 GMT 2009
SunMay0318:04:51 GMT 2009 Measuring Elapsed Time: Sometimes, you may need to measure point in time in milliseconds. So let's rewrite above example once again:
import java dateandtime.util.*;
public class DiffDemo{ public static void main(String args[]){ try{ long start =System.currentTimeMillis(); System.out.println(new Date()+"\n"); Thread.sleep(5*60*10); System.out.println(new Date()+"\n"); longend=System.currentTimeMillis(); long diff =end- start; System.out.println("Difference is : "+ diff); }catch(Exception e){ System.out.println("Got an exception!"); } } } This would produce the following result:
SunMay0318:16:51 GMT 2009
SunMay0318:16:57 GMT 2009 Differenceis:5993 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 Calendar class in this tutorial, 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. There are also several constructors for GregorianCalendar objects:
import java dateandtime.util.*;
public class GregorianCalendarDemo{ public static void main(String args[]){ String months[]={ "Jan","Feb","Mar","Apr", "May","Jun","Jul","Aug", "Sep","Oct","Nov","Dec"}; int year; //Create a Gregorian calendar initialized //with the current date and time in the //default locale and timezone. GregorianCalendar gcalendar =new GregorianCalendar(); // Display current time and date information. System.out.print("Date: "); System.out.print(months[gcalendar.get(Calendar.MONTH)]); System.out.print(" "+ gcalendar.get(Calendar.DATE)+" "); System.out.println(year = gcalendar.get(Calendar.YEAR)); System.out.print("Time: "); System.out.print(gcalendar.get(Calendar.HOUR)+":"); System.out.print(gcalendar.get(Calendar.MINUTE)+":"); System.out.println(gcalendar.get(Calendar.SECOND)); // Test if the current year is a leap year if(gcalendar.isLeapYear(year)){ System.out.println("The current year is a leap year"); } else{ System.out.println("The current year is not a leap year"); } } } This would produce the following result:
Date:Apr222009
Time:11:25:27 The current year is not a leap year For a complete list of constant available in Calendar class, you can refer to standard Java documentation. |