Last active
January 16, 2019 05:28
-
-
Save udoyen/64f2258b537acb58040c17499905b1e6 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// create a java calendar instance | |
Calendar calendar = Calendar.getInstance(); | |
// get a java date (java.util.Date) from the Calendar instance. | |
// this java date will represent the current date, or "now". | |
java.util.Date currentDate = calendar.getTime(); | |
// now, create a java.sql.Date from the java.util.Date | |
java.sql.Date date = new java.sql.Date(currentDate.getTime()); | |
// Condensed form | |
// java.util.Date | |
java.util.Date currentDate = Calendar.getInstance().getTime(); | |
// java.sql.Date | |
Calendar calendar = Calendar.getInstance(); | |
java.sql.Date ourJavaDateObject = new java.sql.Date(calendar.getTime().getTime()); | |
// Condensed java sql date form | |
java.sql.Date ourJavaDateObject = new java.sql.Date(Calendar.getInstance().getTime().getTime()); | |
// Ssample code | |
public class JavaCurrentDateTimeExample | |
{ | |
public static void main(String[] args) throws Exception | |
{ | |
// (1) connect to the database (mysql) | |
String myDriver = "org.gjt.mm.mysql.Driver"; | |
String myUrl = "jdbc:mysql://localhost/date_time_tests"; | |
Class.forName(myDriver); | |
Connection connection = DriverManager.getConnection(myUrl, "root", "root"); | |
// (2) create a java sql date object we want to insert | |
Calendar calendar = Calendar.getInstance(); | |
java.sql.Date ourJavaDateObject = new java.sql.Date(calendar.getTime().getTime()); | |
// (3) create our date insert statement | |
String query = "INSERT INTO datetests (date1) VALUES (?)"; | |
PreparedStatement st = connection.prepareStatement(query); | |
st.setDate(1, ourJavaDateObject); | |
// (4) execute the insert statement, then shut everything down | |
st.executeUpdate(); | |
st.close(); | |
System.exit(0); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment