I have a Date format in java that I need to save as a Time format in MySQL. Is there a way to just get the time part from the date? I know Dat.gettime() that returns a long but I just need the Time in MySql
Any suggestions...
Thx all ..
I have a Date format in java that I need to save as a Time format in MySQL. Is there a way to just get the time part from the date? I know Dat.gettime() that returns a long but I just need the Time in MySql
Any suggestions...
Thx all ..
Using a PreparedStatement together with a java.sql.Time object created from your java.util.Date should work:
java.util.Date myDate = .... java.sql.Time theTime = new java.sql.Time(myDate.getTime()); PreparedStatement pstmt = ... pstmt.setTime(1, theTime); java.sql.Time class is now legacy, supplanted by the java.time.LocalTime class as of JDBC 4.2 and later.When exchanging data with a database, use appropriate date types and objects. Do not use mere strings or integers instead of legitimate types/classes.
The modern approach uses java.time classes. With a JDBC driver complying with JDBC 4.2 or later, you can omit the use of java.sql.Time class, and just use java.time.LocalTime directly.
The legacy class java.util.Date represents a date and a time-of-day in UTC. Convert to a modern java.time class (Instant), assign a time zone through which you want to view the value, and extract the time-of-day.
To convert, call new methods added to the old legacy classes.
Instant instant = myJavaUtilDate.toInstant() ; Assign a time zone.
The time zone is crucial. For any given moment, the date varies around the globe by zone. For example, a few minutes after midnight in Paris France is a new day while still “yesterday” in Montréal Québec.
Specify a proper time zone name in the format of continent/region, such as America/Montreal, Africa/Casablanca, or Pacific/Auckland. Never use the 3-4 letter abbreviation such as EST or IST as they are not true time zones, not standardized, and not even unique(!).
ZoneId z = ZoneId.of( "America/Montreal" ) ; // Or "Asia/Kolkata", or "Pacific/Auckland", etc. ZonedDateTime zdt = instant.atZone( z ) ; Extract the time-of-day without a date.
LocalTime lt = zdt.toLocalTime() ; Pass into your PreparedStatement by calling setObject.
String sql = "INSERT INTO tbl_ ( time_of_day_ ) VALUES ( ? ) ; " ; PreparedStatement ps = conn.prepareStatement( sql ) ; ps.setObject( 1 , lt ) ; // Call `setObject` to pass a java.time object directly without converting into `java.sql.*` type. int rows = ps.executeUpdate() ; Fetch data in a similar manner, calling ResultSet::getObject.
LocalTime lt = myResultSet.getObject( … , LocalTime.class ) ;