Hello Friends,
This is one of my tutorials regarding java Date format / object in Java. Many of us find it difficult to store the current date from the java application in database. Lets consider MySql as a database in this case. Now when we create a row in the database table that
stores date value in the date format (not datetime).
When we use the Date Object to get the current date in Java application then it outputs the date in the format similar to–
“Mon Oct 18 13:26:05 IST 2010”.
1 2 3 4 5 6 7 8 9 |
import java.util.*; public class DateExample { public static void main(String args[]) { Date dateValue = new Date(); System.out.println("The date value:" + dateValue); } } |
This will output something like~
1 |
The date value: Mon Oct 18 19:39:53 IST 2010 |
And if you want to save this date as it is then it will throw an error.
So if you want to save the current date in database in the manner that it takes (usually yyyy/mm/dd), you have to format the
current date format into that similar to the database.
For this formatting java provides the SimpleDateFormat class. For using this class one has to import the package– java.text.SimpleDateFormat
Once you create the object of this format class you can format the date in the manner you want by providing the type of format.
Following is the snnipet for the same.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 |
import java.sql.Timestamp; import java.text.SimpleDateFormat; import java.util.*; public class DateExample { public static void main(String args[]) { Date dateValue = new Date(); System.out.println("The date value******* " + dateValue); SimpleDateFormat formatter = new SimpleDateFormat("yyyy/mm/dd"); String newDateValue = formatter.format(dateValue); System.out.println("The new date value******* " + newDateValue); } } |
The output for this code after formatting the date will be-
1 2 |
The date value******* Mon Oct 18 19:39:53 IST 2010 The new date value******* 2010/39/18 |
This is the simple way to save the date in simple format in the database.
Hope this will help you.
Thanks,
Nikhil.