- 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 do I create a java.sql.Date object in Java?
Using the Constructor
The java.sql.Date represents the date value in JDBC. The constructor of this class accepts a long value representing the desired date and creates respective Date object.
Date(long date)
You can create this object using this constructor.
Example
import java.text.ParseException; import java.text.SimpleDateFormat; public class Demo { public static void main(String args[]) throws ParseException { String str = "26-09-1989"; SimpleDateFormat obj = new SimpleDateFormat("dd-MM-yyyy"); long epoch = obj.parse(str).getTime(); System.out.println("Date value: "+epoch); //Creating java.util.Date object java.util.Date date = new java.util.Date(epoch); System.out.println(date); } }
Output
Date value: 622751400000 Tue Sep 26 00:00:00 IST 1989
Using the valueOf() method
The valueOf() method of this class has two variants as shown below −
- valueOf(LocalDate date);
- valueOf(String s);
This method accepts a LocalDate object or a date string value (yyyy-[m]m-[d]d format) representing a desired date and creates/returns a java.sql.Date object.
Example
import java.sql.Date; import java.time.LocalDate; public class Demo { public static void main(String args[]) { LocalDate localDate = LocalDate.of(2014, 9, 11); Date date = Date.valueOf(localDate); System.out.println(date); } }
Output
Date Value: 2014-09-11
Example
import java.sql.Date; public class Demo { public static void main(String args[]) { String str = "2017-12-03"; Date date = Date.valueOf(str); System.out.println("Date Value: "+date); } }
Output
yyyy-[m]m-[d]d
Advertisements
To Continue Learning Please Login
Login with Google