java tutorial - Java - Date and Time - java programming - learn java - java basics - java for beginners



The Java programming language provides the Date class offered in the java.util package; this class encapsulates the present date and time.

Constructors

  • The Date class supports two constructors as shown in the following table.
No. Constructor and Description
1 Date ()
This constructor initializes an object with the current date and time.
2 Date (long millisec)
This constructor takes an argument equal to the number of milliseconds that have elapsed since midnight on January 1, 1970

Date class methods

  • Below are the methods of the Date class.
No. Methods with a description
1 boolean after (Date date)
Returns true if the calling date object contains a date that is later than the specified date, otherwise it returns false.
2 boolean before (Date date)
Returns true if the calling date object contains a date earlier than the specified date, otherwise it returns false.
3 Object clone ()
Duplicate the calling object date.
4 int compareTo (Date date)
Compares the value of the calling object with this date. Returns 0 if the values are equal. Returns a negative value if the call object is earlier than the date. Returns a positive value if the call object is later than the date.
5 int compareTo (Object obj)
Works exactly the same compareTo (Date) if the call object has a Date class. Otherwise, it calls ClassCastException.
6 boolean equals (Object date)
Returns true if the calling date object contains similar time as well as date which are specified in date, or else it returns false.
7 long getTime ()
Returns the number of milliseconds that elapsed since January 1, 1970.
8 int hashCode ()
Returns the hash code for the calling object.
9 void setTime (long time)
Sets the date and time corresponding to the time point, which represents the total time spent in milliseconds from midnight on January 1, 1970.
10 String toString ()
Converts the calling date object to a string and returns the result.

Current date and time in Java

  • Getting the current date and time in Java is not hard enough. You can use a simple date object with the toString () method to display the current date and time as follows:
import 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());
   }
}
click below button to copy the code. By - java tutorial - team

Output

on May 04 09:51:52 CDT 2009

Comparing dates

Following are the three ways to compare two dates −

  • You can use the getTime () function to get the number of milliseconds that have elapsed since midnight on January 1, 1970, for both objects, and then compare these two values.
  • You can use the methods before (), after (), and equals (). Since the 12th of the month is earlier than the 18th date, for example, new Date (99, 2, 12) .before (new Date (99, 2, 18)) returns true.
  • You also use compareTo () method, that is defined by a comparable interface and then implemented by date.

Formatting a Date with SimpleDateFormat

SimpleDateFormat is a concrete class for parsing and formatting dates in Java. SimpleDateFormat allows you to start by selecting any custom templates for formatting the date and time. 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));
   }
}
click below button to copy the code. By - java tutorial - team

Output

Current Date: Sun 2004.07.18 at 04:14:09 PM PDT

SimpleDateFormat format codes

  • To specify the time format, use a time pattern string. In this pattern, all the ASCII letters are reserved as pattern letters, that are defined as the following −
The Description Example
G The era designation AD
y Four-digit year 2016
M Month of the year number 11
d Number of the month 13
h Hour format in A.M./P.M. (1 ~ 12) 7
H Hour format (0 ~ 23) 19
m Minutes 30
s Seconds 45
S Milliseconds 511
E Day of the week Sun
D Number of the day of the year 318
F The day of the week in the month 2 (the second Sunday in this month)
w Week number in the year 46
W The week number in the month 2
a Marker A.M./P.M. AM
k Hour format (1 ~ 24) 24
K Hour format in A.M./P.M.(0~11) 0
z Time Zone FET (Far Eastern European Time)
' Highlighting for text Text
'' Single quotation mark '

Date Formatting Using printf

  • The format of the date and time can be made easily with the printf method. You use a two-letter format, starting with t and ending with one of the symbols in the table below. For example:
import 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);
   }
}
click below button to copy the code. By - java tutorial - team

Output

Current Date/Time : Sat Dec 15 16:37:57 MST 2012
  • It would be a bit silly if you would have to put the date several times to format each part. For this reason, the string format can indicate the argument index for formatting.

The index should directly follow% and terminate $. For example:

Sample Code

import 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);
   }
}
click below button to copy the code. By - java tutorial - team

Output

Due date: February 09, 2004
  • In addition, you can use < This means that the same argument should be used again, like the previous format specifications. For example:

Sample Code

import 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);
   }
}
click below button to copy the code. By - java tutorial - team

Output

Due date: February 09, 2004

Date and Time Conversion Characters

  • In Java, you can implement the date output in the correct format using the following conversion characters:
The Description Example
c Current time and date Sun Nov 13 01:19:27 FET 2016
F Date format ISO 8601 (year-month-day) 2016-11-13
D American date format (month / day / year) 11/13/16
T 24-hour time format 01:26:09
r 12-hour time format 01:26:51 AM
R 24-hour time format without seconds 01:27
Y Current year of four digits (with leading zeros) 2016
y Last two digits of the year (with leading zeros) 16
C The first two digits of the year (with leading zeros) 20
B Full month name November
b Abbreviated month name Nov
m Current month number (with leading zeros) 11
d The number of the current day of the month (with leading zeros) 09
e The number of the current day of the month (without leading zeros) 9
A The full name of the current day of the week Sunday
a Abbreviated day of the week Sun
j Number of days since the beginning of the year (with leading zeros) 318
H Hour format (with leading zeros), from 00 to 23 01
k Hour format (without leading zeros), from 0 to 23 1
I Hour format (with leading zeros), from 01 to 12 01
l Hour format (without leading zeros), from 1 to 12 1
M Minutes (with leading zeros) 38
S Seconds (with leading zeros) 50
L Milliseconds (with leading zeros) 382
N Nanoseconds (with leading zeros) 775000000
p (% Tp) The upper register of the marker is A.M./P.M. AM
p (% tp) Lowercase of the marker A.M./P.M. am
z Hourly offset RFC 822 by GMT +0300
Z Time Zone FET
s Seconds since 1970-01-01 00:00:00 GMT 1478991147
Q Milliseconds since 1970-01-01 00:00:00 GMT 1478991172134

Converting a string to a date

  • The SimpleDateFormat classes have some other methods, notably parse( ), that tries to parse a string along with the format stored in the given SimpleDateFormat object.

Sample Code

import 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); 
      }
   }
}
click below button to copy the code. By - java tutorial - team

Output

1818-11-11 Parses as Wed Nov 11 00:00:00 EST 1818

Time delay

  • You can increase or decrease the running time of the program for any period of time, from one millisecond to the life of your computer. For example, the following program will be in standby mode for 10 seconds:

Sample Code

import 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!"); 
      }
   }
}
click below button to copy the code. By - java tutorial - team

Output

Sun May 03 18:04:41 GMT 2009
Sun May 03 18:04:51 GMT 2009
  • nstead of Thread.sleep (), we recommend using TimeUnit (): TimeUnit.NANOSECONDS.sleep (), TimeUnit.MICROSECONDS.sleep (), TimeUnit.MILLISECONDS.sleep (), TimeUnit.SECONDS.sleep (), TimeUnit.MINUTES.sleep ( ), TimeUnit.HOURS.sleep (), or TimeUnit.DAYS.sleep ().

Class GregorianCalendar

  • The GregorianCalendar is concrete implementation of Calendar class which implements the ordinary Gregorian calendar with that you are well-known.
  • A getInstance( ) method of a Calendar returns the GregorianCalendar which are started with present date and time in a default locale as well as time zone.
  • GregorianCalendar defines two fields. They are AD and BC and represents through two eras which are defined by Gregorian calendar.

There are numerous constructors for GregorianCalendar objects. They are −

No. Constructor and its description
1 GregorianCalendar ()
Creates a GregorianCalendar value, using the default current date and time, localization, and time zone.
2 GregorianCalendar (int year, int month, int date)
Creates GregorianCalendar according to the specified date in the time zone and the default localization.
3 GregorianCalendar (int year, int month, int date, int hour, int minute)
Creates GregorianCalendar according to the specified date and time in the time zone and the default localization.
4 GregorianCalendar (int year, int month, int date, int hour, int minute, int second)
Creates GregorianCalendar according to the specified date and time in the time zone and the default localization.
5 GregorianCalendar (Locale aLocale)

Creates GregorianCalendar according to the current time in the default time zone within the specified localization.
6 GregorianCalendar (TimeZone zone)
Constructs the GregorianCalendar based on the present time in a given time zone with default localization.
7 GregorianCalendar (TimeZone zone, Locale aLocale)
Constructs a GregorianCalendar based on the current time in a given time zone and localization.

A list of several useful methods provided by the GregorianCalendar class:

No. Methods with a description
1 void add (int field, int amount)
Adds the specified amount of time to this temporary field along with the calendar rules.
2 protected void computeFields ()
Converts the GMT time in milliseconds to the value of the time fields.
3 protected void computeTime ()
Converts the values of the temporary Calendar field to UTC format in milliseconds.
4 boolean equals (Object obj)
Compares this GregorianCalendar to a reference object.
5 int get (int field)
Gets the value for the specified time field.
6 int getActualMaximum (int field)
Returns the maximum value of this field can have, given the present date.
7 int getActualMinimum (int field)
Returns the minimum value of this field can have, given the present date.
8 int getGreatestMinimum (int field)
Returns the largest minimum value for a given field, if changed.
9 Date getGregorianChange ()
Gets the date changes according to the Gregorian calendar.
10 int getLeastMaximum (int field)
Returns the minimum value for this field if it is changed.
11 int getMaximum (int field)
Returns the maximum value for this field.
12 Date getTime ()
Determines the current time according to the calendar.
13 long getTimeInMillis ()
Gets the current time in the Calendar as a long time.
14 TimeZone getTimeZone ()
Returns the time zone.
15 int getMinimum (int field)
Returns the minimum value for this field.
16 int hashCode ()
Override the hash code.
17 boolean isLeapYear (int year)
Determines whether a year is a leap year.
18
Adding or subtracting (up / down) one unit of time in a given time field without changes in large fields.
19 void set (int field, int value)
Sets the time field with the specified value.
20 Set the values for the year, month, and date field.
21 Specifies the values for the year, month, date, hour and minute field.
22 Sets the values for the year, month, date, hour, minute and then second field.
23 void setGregorianChange (Date date)
Sets the date of the Gregorian calendar modify (change).
24 void setTime (Date date)
Sets the current time with the specified date according to this calendar.
25 void setTimeInMillis (long millis)
Sets the current time from the specified long value according to this calendar.
26 void setTimeZone (TimeZone value)
Sets the time zone with the value of the specified time zone.
27 String toString ()
Returns the string representation of the calendar.

Example : displaying the current date and time, leap year

import 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");
      }
   }
}
click below button to copy the code. By - java tutorial - team

Output

Date: Apr 22 2009
Time: 11:25:27
The current year is not a leap year

Related Searches to Java - Date and Time