Date, Calendar and Time API Tutorial


In this article I am going to explain using Date, Calendar, Time in Java and how to format the output of the Date object. Java has the following date and time classes and methods.
  • System.currentTimeMillis(): A static method that returns the current date and time as milliseconds since January 1st 1970.
  • java.util.Date: A class that represents a date and time. Most methods in this class is deprecated.
  • java.sql.Date: A class that represents a date. This date class is used with JDBC.
  • java.sql.Timestamp: A class that represents a date and time. This date and time class is used with JDBC.
  • java.util.Calendar: It is an abstract encapsulation of the object Date. The concrete implementation is java.util.GregorianCalendar.
  • java.util.GregorianCalendar: The concrete implementation of the java.util.Calendar.
  • java.util.TimeZone: The Java TimeZone class is a class that represents time zones, and is helpful when doing calendar arithmetics across time zones.
  • java.text.SimpleDateFormat: This class to convert the date into user friendly format.

System.currentTimeMillis():

The static method System.currentTimeMillis() returns the time since January 1st 1970 in milliseconds. The value returned is a long. If you need to do simple timing the System.currentTimeMillis() method will do just fine.
long timeNow = System.currentTimeMillis();
Calculating the time in Java is easiest to do with the System.currentTimeMillis() method.What you can do is that you get the time before and after the operation you want to measure, and calculate the time difference.
long startTime = System.currentTimeMillis();
Operation here...
long endTime   = System.currentTimeMillis();
long totalTime = endTime - startTime;

The variable totalTime will now contain the total time it took to execute the operation.
The java.util.Date and the java.util.Calendar class provides access to storing and manipulating dates. Here is how to instantiate a java.util.Date instance:
java.util.Date date = new java.util.Date();
You can also create a java.util.Date from a time in milliseconds:
long now = System.currentTimeMillis();
java.util.Date date = new java.util.Date(now);
We can compare the two dates using compareTo() method, as the java.util.Date implements the Comparable interface.
Date date1 = new java.util.Date();
Date date2 = new java.util.Date();
date1.compareTo(date2);
If you need to do date calculations like adding days or months to another date, or check what weekday a given date is, or convert dates and times between time zones, use the java.util.Calendar and java.util.GregorianCalendar classes. Java only comes with a Gregorian calendar implementation, the java.util.GregorianCalendar class.
Calendar calendar = new GregorianCalendar();
Calendar provides getter and setter for the date fields.
public final int get(int field)
public final void set(int field, int value)
The Calendar class has a couple of methods you can use to access the year, month, day, hour, minutes, seconds, milliseconds and time zone of a given date.
Calendar calendar = new GregorianCalendar();
int year       = calendar.get(Calendar.YEAR);
int month      = calendar.get(Calendar.MONTH); 
int dayOfMonth = calendar.get(Calendar.DAY_OF_MONTH); //  Month start from 0
int dayOfWeek  = calendar.get(Calendar.DAY_OF_WEEK);
int weekOfYear = calendar.get(Calendar.WEEK_OF_YEAR);
int weekOfMonth= calendar.get(Calendar.WEEK_OF_MONTH);
int hour       = calendar.get(Calendar.HOUR);        // 12 hour clock
int hourOfDay  = calendar.get(Calendar.HOUR_OF_DAY); // 24 hour clock
int minute     = calendar.get(Calendar.MINUTE);
int second     = calendar.get(Calendar.SECOND);
int millisecond= calendar.get(Calendar.MILLISECOND);
If you need to read and write the date and time to a database, use the java.sql.Date and java.sql.Timestamp classes. We can use the java.sql.Date and java.sql.Timestamp when we get the Date and Timestamp object from the Database ResultSet object and into the ResultSet object.

Formatting the Date:

Date() + SimpleDateFormat()
DateFormat df  = new SimpleDateFormat(“MM/dd/yyyy”);
Date date = new Date();
System.out.println(df.format(date));
Calendar() + SimpleDateFormat()
DateFormat df  = new SimpleDateFormat(“MM/dd/yyyy”);
Calendar now = Calendar.getInstance();
System.out.println(df.format(now));

Date Example:



import java.util.Date;

public class DateExample {
  public static void main(String[] args) {
    Date date1 = new Date();

           long now = System.currentTimeMillis();
    Date date2 = new Date(now);

    System.out.println(“Date1:   ” + date1);
    System.out.println(“Date2:   ” + date2);
  }
}


Calendar Example:



import java.text.SimpleDateFormat;
import java.text.DateFormat;
import java.util.Calendar;
import java.util.GregorianCalendar;

public class CalendarExample {
  public static void main(String[] args) {
    Calendar cal = new GregorianCalendar();
    cal.set(Calendar.MONTH, Calendar.MAY);

    System.out.println("Year: " + cal.get(Calendar.YEAR));
    System.out.println("Month: " + (cal.get(Calendar.MONTH) + 1));
    System.out.println("Days: " + cal.get(Calendar.DAY_OF_MONTH));

    DateFormat df = new SimpleDateFormat("MM/dd/yyyy");
    System.out.println(df.format(cal1.getTime()));

  }
}


No comments

Powered by Blogger.