- Trending Categories
- Data Structure
- Networking
- RDBMS
- Operating System
- Java
- MS Excel
- iOS
- HTML
- CSS
- Android
- Python
- C Programming
- C++
- C#
- MongoDB
- MySQL
- Javascript
- PHP
- Physics
- Chemistry
- Biology
- Mathematics
- English
- Economics
- Psychology
- Social Studies
- Fashion Studies
- Legal Studies
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
How to create Date object from String value in Java?
Using the SimpleDateFormat class
One of the constructors of this class accepts a String value representing the desired date format and creates SimpleDateFormat class. To 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
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
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
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