GeezerVisonThe World Wide Web, restored to 800 pixels of glory. | |||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
| Home|About|Gaming cabinet|Archives|How it works|Starter sites | |||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
GeezerVison is showing www.tutorialspoint.com — Java - Date and Time
Selected Reading
Java - Date and TimeJava provides the Date class available in java.util package, this class encapsulates the current date and time. The Date class supports two constructors as shown in the following table.
Following are the methods of the date class.
Getting Current Date and TimeThis is a very easy method to get current date and time in Java. You can use a simple Date object with toString() method to print the current date and time as follows − Exampleimport java.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.println(date.toString());
}
}
This will produce the following result − Outputon May 04 09:51:52 CDT 2009 Date ComparisonFollowing are the three ways to compare two dates −
Date Formatting Using SimpleDateFormatSimpleDateFormat 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. Exampleimport 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 will produce the following result − OutputCurrent Date: Sun 2004.07.18 at 04:14:09 PM PDT Simple DateFormat Format CodesTo 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 Formatting Using printfDate 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 as shown in the following code. Exampleimport java.util.Date;
public class DateDemo {
public static void main(String args[]) {
// Instantiate a Date object
Date date = new Date();
// display time and date
String str = String.format("Current Date/Time : %tc", date );
System.out.printf(str);
}
}
This will produce the following result − OutputCurrent Date/Time : Sat Dec 15 16: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 $. Exampleimport java.util.Date;
public class DateDemo {
public static void main(String args[]) {
// Instantiate a Date object
Date date = new Date();
// display time and date
System.out.printf("%1$s %2$tB %2$td, %2$tY", "Due date:", date);
}
}
This will produce the following result − OutputDue date: February 09, 2004 Alternatively, you can use the < flag. It indicates that the same argument as in the preceding format specification should be used again. Exampleimport java.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 %<te, %<tY", "Due date:", date);
}
}
This will produce the following result − OutputDue date: February 09, 2004 Date and Time Conversion Characters
There are other useful classes related to Date and time. For more details, you can refer to Java Standard documentation. Parsing Strings into DatesThe SimpleDateFormat class has some additional methods, notably parse( ), which tries to parse a string according to the format stored in the given SimpleDateFormat object. Exampleimport java.util.*;
import java.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 − Output1818-11-11 Parses as Wed Nov 11 00:00:00 EST 1818 Sleeping for a WhileYou can sleep for any period of time from one millisecond up to the lifetime of your computer. For example, the following program would sleep for 3 seconds − Exampleimport java.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 will produce the following result − OutputSun May 03 18:04:41 GMT 2009 Sun May 03 18:04:51 GMT 2009 Measuring Elapsed TimeSometimes, you may need to measure point in time in milliseconds. So let's re-write the above example once again − Exampleimport java.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");
long end = System.currentTimeMillis( );
long diff = end - start;
System.out.println("Difference is : " + diff);
} catch (Exception e) {
System.out.println("Got an exception!");
}
}
}
This will produce the following result − OutputSun May 03 18:16:51 GMT 2009 Sun May 03 18:16:57 GMT 2009 Difference is : 5993 GregorianCalendar ClassGregorianCalendar is a concrete implementation of a Calendar class that implements the normal Gregorian calendar with which you are familiar. We did not discuss Calendar class in this tutorial, you can look up 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 −
Here is the list of few useful support methods provided by GregorianCalendar class −
Exampleimport java.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 will produce the following result − OutputDate: Apr 22 2009 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 the standard Java documentation. Advertisements
| |||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
| You are visitor 01402503 — GeezerVison does not store the pages you look up. Best viewed with Netscape Navigator 4.7 or Internet Explorer 6 at 800×600. No cookies required. |