How to parse date sting to date in Java?

JavaServer Side ProgrammingProgramming

You can parse a string containing a data to date value using the following ways −

  • The constructor SimpleDateFormat class accepts a String value representing the desired date format and creates this objectYou can parse the date string using the parse() method of this class.
  • The parse() method of the LocalDate class accepts a String value representing a date and returns a LocalDate object.
  • The DateUtils provides utility to format date you can find it in apache.commons package. The parseDate() method of the DateUtils class accepts a format string and a date string as parameters and returns a Date object.
  • 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.

Using the SimpleDateFormat class

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

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:

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

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:58:48
Advertisements