How to create date object in Java?

JavaServer Side ProgrammingProgramming

Using the Date class

You can create a Date object using the Date() constructor of java.util.Date constructor as shown in the following example. The object created using this constructor represents the current time.

Example

Live Demo

import java.util.Date;
public class CreateDate {
   public static void main(String args[]) {      
      Date date = new Date();
      System.out.print(date);
   }
}

Output

Thu Nov 02 15:43:01 IST 2018

Using the SimpleDateFormat class

Using the SimpleDateFormat class and the parse() method of this you can parse a date string in the required format and create a Date object representing the specified date.

Example

Live Demo

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
public class Test {
   public static void main(String args[]) throws ParseException {  
       String date_string = "26-09-1989";
       //Instantiating the SimpleDateFormat class
       SimpleDateFormat formatter = new SimpleDateFormat("dd-MM-yyyy");      
       //Parsing the given String to Date object
       Date date = formatter.parse(date_string);      
       System.out.println("Date value: "+date);
   }
}

Output

Date value: Tue Sep 26 00:00:00 IST 1989

Using the LocalDate class

A LocalDate object is similar to the date object except it represents the date without time zone, you can use this object instead of Date.

  • The now() method of this class returns a LocalDate object representing the current time
  • The of() method accepts the year, month and day values as parameters an returns the respective LocalDate object.
  • The parse() method accepts a date-string as a parameter and returns the LocalDate object5 representing the given date.

Example

Live Demo

import java.time.LocalDate;
public class Test {
   public static void main(String args[]) {  
      LocalDate date1 = LocalDate.of(2014, 9, 11);
      System.out.println(date1);
      LocalDate date2 = LocalDate.parse("2007-12-03");
      System.out.println(date2);
      LocalDate date3 = LocalDate.now();
      System.out.println(date3);
   }
}

Output

2014-09-11
2007-12-03
2020-11-05
raja
Published on 05-Feb-2021 10:39:20
Advertisements