
If you want to try to repeat this example on your system, here's the schema for the "current date" test database table that was used in our JavaCurrentDateTimeExample program:Ĭonfirming the current date in the databaseĪfter running my JavaCurrentDateTimeExample program, I logged into my MySQL database and checked my datetests database table to make sure it contained the current date with this SQL query:Īs you can see, this "current date" approach works just fine.
#Java setdate how to#
(4) execute the insert statement, then shut everything downĪs you can see, this sample Java program shows how to connect to a MySQL database, construct a Java Date object, create a SQL INSERT statement, use that INSERT statement in a Java PreparedStatement, and then execute this SQL INSERT statement, which inserts our Java current date into the database. PreparedStatement st = connection.prepareStatement(query) String query = "INSERT INTO datetests (date1) VALUES (?)" (2) create a java sql date object we want to insert This is the Java data model class that specifies how to parse/serialize into the JSON that is. String myUrl = "jdbc:mysql://localhost/date_time_tests" Ĭonnection connection = DriverManager.getConnection(myUrl, "root", "root") Public static void main(String args) throws Exception But, if you want to see how to use that Java current date object in a complete SQL INSERT example, the following Java program demonstrates every step you need to insert the current date into the date field of a SQL database table, including the initial database connection: If you just wanted to see how to construct a object to represent the current date, that's probably all you need to know. No matter which approach you take, those are the steps required to create a to represent the current date and time (i.e., "now"). ourJavaDateObject = new (Calendar.getInstance().getTime().getTime()) I saved the date as a string in the database. Or for the, even into one line, like this: I have a form on which I want to access a date from the database and show in jDateChooser for a particular record. ourJavaDateObject = new (calendar.getTime().getTime())

currentDate = Calendar.getInstance().getTime()


#Java setdate code#
I showed that code fully expanded so you can see what you need to do, but once you understand that background, you can condense that code some more, like this: this java date will represent the current date, or "now". get a java date () from the Calendar instance. Solution: You can create a Java Date object to represent the current date in just a few lines of code, as shown in the following code:Ĭalendar calendar = Calendar.getInstance() Java current date FAQ: When working with a Date in Java, how do I create a Java Date ( ) object to represent the current date (i.e., "now")? Java current date - solution
