How to create Date object from String value in Java?

JavaServer Side ProgrammingProgramming

Using the SimpleDateFormat class

One of the constructors of this class accepts a String value representing the desired date format and creates SimpleDateFormat classTo parse/convert a string as a Date object −

  • Instantiate this class by passing desired format string.
  • Parse the date string using the parse() method.

Example

Live Demo

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

Output

Date value: Mon Jun 25 00:00:00 IST 2007

Using the LocalDate class

The parse() method of the LocalDate class accepts a String value representing a date and returns a LocalDate object.

Example

Live Demo

import java.time.LocalDate;
public class Test {
   public static void main(String args[]) {  
      LocalDate date = LocalDate.parse("2007-12-03");
      System.out.println(date);
   }
}

Output

2007-12-03

Using the DateUtils class:

The DateUtils provides utility to format date you can find it in apache.commons package following is the maven dependency for the package −

<dependency>
    <groupId>org.apache.commons</groupId>
    <artifactId>commons-lang3</artifactId>
    <version>3.7</version>
</dependency>

The parseDate() method of the DateUtils class accepts a format string and a date string as parameters and returns a Date object.

Example

import java.util.Date;
import org.apache.commons.lang3.time.DateUtils;
public class Test {
   public static void main(String args[]) {  
      String dateInString = "07-06-2013";
      Date date = DateUtils.parseDate(dateInString, "yyyy-MM-dd");
      System.out.println(date);
   }
}

Output

Sat Dec 03 00:00:00 IST 12

Using the Instant class

The parse() method of the java.time.Instant class accepts a date string as a parameter and returns an object (Instant) representing the given date.

Example

Live Demo

import java.time.Instant;
public class Test {
   public static void main(String args[]) {  
      String dateInString = "2014-10-05T15:23:01Z";
      Instant instant = Instant.parse(dateInString);
      System.out.println(instant);
   }
}

Output

2014-10-05T15:23:01Z

raja
Published on 06-Feb-2021 03:44:24
Advertisements