close
The Wayback Machine - https://web.archive.org/web/20241009111348/https://www.geeksforgeeks.org/date-class-java-examples/
Open In App

Date class in Java (With Examples)

Last Updated : 02 Jan, 2019
Summarize
Comments
Improve
Suggest changes
Like Article
Like
Save
Share
Report
News Follow

The class Date represents a specific instant in time, with millisecond precision. The Date class of java.util package implements Serializable, Cloneable and Comparable interface. It provides constructors and methods to deal with date and time with java.

Constructors

  • Date() : Creates date object representing current date and time.
  • Date(long milliseconds) : Creates a date object for the given milliseconds since January 1, 1970, 00:00:00 GMT.
  • Date(int year, int month, int date)
  • Date(int year, int month, int date, int hrs, int min)
  • Date(int year, int month, int date, int hrs, int min, int sec)
  • Date(String s)
  • Note : The last 4 constructors of the Date class are Deprecated.




    // Java program to demonstrate constuctors of Date
    import java.util.*;
      
    public class Main
    {
        public static void main(String[] args)
        {
            Date d1 = new Date();
            System.out.println("Current date is " + d1);
            Date d2 = new Date(2323223232L);
            System.out.println("Date represented is "+ d2 );
        }
    }

    
    

    Output:

    Current date is Tue Jul 12 18:35:37 IST 2016
    Date represented is Wed Jan 28 02:50:23 IST 1970
    

    Important Methods

    • boolean after(Date date) : Tests if current date is after the given date.
    • boolean before(Date date) : Tests if current date is before the given date.
    • int compareTo(Date date) : Compares current date with given date. Returns 0 if the argument Date is equal to the Date; a value less than 0 if the Date is before the Date argument; and a value greater than 0 if the Date is after the Date argument.
    • long getTime() : Returns the number of milliseconds since January 1, 1970, 00:00:00 GMT represented by this Date object.
    • void setTime(long time) : Changes the current date and time to given time.




    // Program to demonstrate methods of Date class
    import java.util.*;
      
    public class Main
    {
        public static void main(String[] args)
        {
            // Creating date
            Date d1 = new Date(2000, 11, 21);
            Date d2 = new Date();  // Current date
            Date d3 = new Date(2010, 1, 3);
      
            boolean a = d3.after(d1);
            System.out.println("Date d3 comes after " +
                               "date d2: " + a);
      
            boolean b = d3.before(d2);
            System.out.println("Date d3 comes before "+
                               "date d2: " + b);
      
            int c = d1.compareTo(d2);
            System.out.println(c);
      
            System.out.println("Miliseconds from Jan 1 "+
                    "1970 to date d1 is " + d1.getTime());
      
            System.out.println("Before setting "+d2);
            d2.setTime(204587433443L);
            System.out.println("After setting "+d2);
        }
    }

    
    

    Output:

    Date d3 comes after date d2: true
    Date d3 comes before date d2: false
    1
    Miliseconds from Jan 1 1970 to date d1 is 60935500800000
    Before setting Tue Jul 12 13:13:16 UTC 2016
    After setting Fri Jun 25 21:50:33 UTC 1976
    


Similar Reads

Difference Between java.sql.Time, java.sql.Timestamp and java.sql.Date in Java
Across the software projects, we are using java.sql.Time, java.sql.Timestamp and java.sql.Date in many instances. Whenever the java application interacts with the database, we should use these instead of java.util.Date. The reason is JDBC i.e. java database connectivity uses these to identify SQL Date and Timestamp. Here let us see the differences
7 min read
util.date class methods in Java with Examples
Following are some important date class methods : .toString() : java.util.Date.tostring() method is a java.util.Date class method.It displays the Current date and time. Here Date object is converted to a string and represented as: day mon dd hh:mm:ss zz yyyy day : day of the week mon : month dd : day of the month hh : hour mm : minute ss : second z
5 min read
Date before() method in Java with Examples
The before() method of Java Date class tests whether the date is before the specified date or not. Syntax: public boolean before(Date when) Parameters: The function accepts a single parameter when which specifies the date that has to be checked. Return Value: It returns a Boolean value. It will return true if this date is before the specified date
2 min read
Date compareTo() method in Java with examples
The compareTo() method of Java Date class compares two dates and sort them for order. Syntax: public int compareTo(Date anotherDate) Parameters: The function accepts a single parameter anotherDate which specifies the date to be compared . Return Value: The function gives three return values specified below: It returns the value 0 if the argument Da
2 min read
Date equals() method in Java with Examples
The equals() method of Java Date class checks if two Dates are equal, based on millisecond difference. Syntax: public boolean equals(Object obj) Parameters: The function accepts a single parameter obj which specifies the object to be compared with. Return Value: The function gives 2 return values specified below: true if the objects are equal. fals
2 min read
Date toString() method in Java with Examples
The toString() method of Java Date class converts this date object into a String in form "dow mon dd hh:mm:ss zzz yyy". This method overrides toString in class object. Syntax: public String toString() Parameters: The function does not accept any parameter. Return Value: It method returns a string representation of this date. Exception: The function
2 min read
Date hashCode() method in Java with Examples
The hashCode() method of Java Date class returns a value which is a hash code for this object. Syntax: public int hashCode() Parameters: The function does not accept any parameter. Return Value: It returns a hashCode value for this object. Exception: The function does not throws any exception. Program below demonstrates the above mentioned function
2 min read
Date setTime() method in Java with Examples
The setTime() method of Java Date class sets a date object. It sets date object to represent time milliseconds after January 1, 1970 00:00:00 GMT. Syntax: public void setTime(long time) Parameters: The function accepts a single parameter time which specifies the number of milliseconds. Return Value: It method has no return value. Exception: The fun
2 min read
Date getTime() method in Java with Examples
The getTime() method of Java Date class returns the number of milliseconds since January 1, 1970, 00:00:00 GTM which is represented by Date object. Syntax: public long getTime() Parameters: The function does not accept any parameter. Return Value: It returns the number of milliseconds since January 1, 1970, 00:00:00 GTM. Exception: The function doe
2 min read
Date toInstant() Method in Java with Examples
The toInstant() method of Date class in Java is used to convert a Date object to an Instant object. An Instant is created during the conversion which is used to represent the same point on the timeline as this Date. Syntax: public Instant toInstant() Parameters: The method does not take any parameters. Return Value: The method returns an Instant re
2 min read
Date clone() method in Java with Examples
The clone() method of Date class in Java returns the duplicate of the passed Date object. This duplicate is just a shallow copy of the given Date object.Syntax: public Object clone() Parameters: The method does not accept any parameters.Return Value: The method returns a clone of the object.Below programs illustrate the use of clone() Method:Exampl
2 min read
Date from() method in Java with Examples
The from(Instant inst) method of Java Date class returns an instance of date which is obtained from an Instant object. Syntax: public static Date from(Instant inst) Parameters: The method takes one parameter inst of Instant type which is required to be converted. Return Value: The method returns a date representing the same point on the timeline as
2 min read
LocalDateTime of(date, time) method in Java with Examples
The of(LocalDate date, LocalTime time) method of LocalDateTime class in Java is used to obtain an instance of LocalDateTime using the two input parameters, date and time. Initially, two separate instances are created. One is of LocalDate type and the other one is of LocalTime type. Then these are merged to create a LocalDateTime. Syntax: public sta
2 min read
Java.util.concurrent.RecursiveAction class in Java with Examples
RecursiveAction is an abstract class encapsulates a task that does not return a result. It is a subclass of ForkJoinTask, which is an abstract class representing a task that can be executed on a separate core in a multicore system. The RecursiveAction class is extended to create a task that has a void return type. The code that represents the compu
3 min read
Java.util.concurrent.Phaser class in Java with Examples
Phaser's primary purpose is to enable synchronization of threads that represent one or more phases of activity. It lets us define a synchronization object that waits until a specific phase has been completed. It then advances to the next phase until that phase concludes. It can also be used to synchronize a single phase, and in that regard, it acts
7 min read
Java.util.concurrent.RecursiveTask class in Java with Examples
RecursiveTask is an abstract class encapsulates a task that returns a result. It is a subclass of ForkJoinTask. The RecursiveTask class is extended to create a task that has a particular return type. The code that represents the computational portion of the task is kept within the compute() method of RecursiveTask. RecursiveTask class is mostly use
2 min read
Java class dependency analyzer in Java 8 with Examples
Java class dependency analyzer: jdeps is a new command-line tool introduced in JDK 8 to understand the static dependencies and libraries of application i.e. jdeps command shows the package-level or class-level dependencies of Java class files. The input for jdeps can be a .class file pathname, a JAR file or it can be a fully qualified class name to
2 min read
Java.util.BitSet class in Java with Examples | Set 1
BitSet is a class defined in the java.util package. It creates an array of bits represented by boolean values. Constructors: BitSet class Constructors / \ BitSet() BitSet(int no_Of_Bits)BitSet() : A no-argument constructor to create an empty BitSet object. BitSet(int no_Of_Bits): A one-constructor with an integer argument to create an instance of t
2 min read
Java.util.BitSet class methods in Java with Examples | Set 2
Methods discussed in this post: BitSet class methods. / / | | \ \ set() xor() clone() clear() length() cardinality() We strongly recommend to refer below set 1 as a prerequisite of this. BitSet class in Java | Set 1 set() : java.util.BitSet.set() method is a sets the bit at the specified index to the specified value. Syntax:public void set(int bitp
4 min read
Java.awt.image.RescaleOp Class in Java with Examples
RescaleOp is a class in java.awt.image package which implements BufferedImageOp and RasterOp interface. This class performs a pixel-by-pixel rescaling of the data in the source image by multiplying the sample values for each pixel by a scale factor and then adding an offset. The scaled sample values are clipped to the minimum/maximum representation
5 min read
Java.lang.Class class in Java | Set 1
Java provides a class with name Class in java.lang package. Instances of the class Class represent classes and interfaces in a running Java application. The primitive Java types (boolean, byte, char, short, int, long, float, and double), and the keyword void are also represented as Class objects. It has no public constructor. Class objects are cons
15+ min read
Java.lang.Class class in Java | Set 2
Java.lang.Class class in Java | Set 1 More methods: 1. int getModifiers() : This method returns the Java language modifiers for this class or interface, encoded in an integer. The modifiers consist of the Java Virtual Machine's constants for public, protected, private, final, static, abstract and interface. These modifiers are already decoded in Mo
15+ min read
New Date-Time API in Java 8
New date-time API is introduced in Java 8 to overcome the following drawbacks of old date-time API : Not thread safe : Unlike old java.util.Date which is not thread safe the new date-time API is immutable and doesn't have setter methods.Less operations : In old API there are only few date operations but the new API provides us with many date operat
6 min read
Date after() method in Java
The java.util.Date.after() method is used to check whether the current instance of the date is after the specified date. Syntax: dateObject.after(Date specifiedDate) Parameter: It takes only one parameter specifiedDate of data type Date. This is the date which is to be checked in comparison to the instance of the date calling the function. Return V
2 min read
Program to Convert Milliseconds to a Date Format in Java
Given milliseconds. The task is to write a program in Java to convert Milliseconds to a Date that Displays the date in dd MMM yyyy HH:mm:ss:SSS Z format.The Date class in Java internally stores Date in milliseconds. So any date is the number of milliseconds passed since January 1, 1970, 00:00:00 GMT and the Date class provides a constructor which c
2 min read
Java Program to Convert String to Date
Given a string in date format, the task is to convert this String into an actual date. Here the main concept is the parse() method which helps in the conversion. Illustration: Input : string = "2018-10-28T15:23:01Z" Output: 2018-10-28T15:23:01Z Input : string = "28 October, 2018" Output: 2018-10-28Different Methods to Convert String to DateUsing in
4 min read
DateFormat format(Date obj) method in Java
The format() method of DateFormat class in Java is used to format a given Date object into a string representing Date/Time.Syntax: String format(Date date) Parameters: This method accepts a single parameter date which is a Date object. Return Value: This method returns a String which is the formatted date-time value of the Date object passed as a p
2 min read
HijrahChronology date() method in Java with Example : Set - 1
The date() method of java.time.chrono.HijrahChronology class is used get the local date according to Hijrah calendar system for the given year, month and day.Syntax: public HijrahDate date(int prolepticYear, int month, int day) Parameter: This method takes the following arguments as parameter. prolepticYear: integer proleptic year for the year fiel
2 min read
HijrahChronology date() method in Java with Example : Set - 2
The date() method of java.time.chrono.HijrahChronology class is used get the local date according to Hijrah calendar system from the another TemporalAccessor object . Syntax: public HijrahDate date(TemporalAccessor temporal) Parameter: This method takes the object of any temporal accessor as a parameter. Return Value: This method returns the local
2 min read
IsoChronology date(int, int, int) method in Java with Example
The date() method of java.time.chrono.IsoChronology class is used get the local date according to ISO calendar system for the given year, month and day. Syntax: public LocalDate date(int prolepticYear, int month, int dayOfMonth) Parameter: This method takes the following arguments as parameter. prolepticYear: integer proleptic year for the year fie
2 min read
Article Tags :
Practice Tags :