Java Date & # 8594; on MySql Time

I have a Date format in java that I need to save as a Time format in MySQL. Is there any way to get time from date? I know Dat.gettime (), which returns long, but I just need time in MySql

Any suggestions...

thanks all ..

+3
source share
6 answers

Using PreparedStatement along with an object java.sql.Timecreated from yours java.util.Dateshould work:

java.util.Date myDate = ....
java.sql.Time theTime = new java.sql.Time(myDate.getTime());
PreparedStatement pstmt = ...
pstmt.setTime(1, theTime);
+3
source

Use java.sql.Date to create the SQL date.

long d = date.getTime();
java.sql.Date sqlDate = new java.sql.Date(d);
0
source

SimpleDateFormat :

SimpleDateFormat sdf =  new SimpleDateFormat("HH:mm:ss" );
String time = sdf.format (  yourDate  );
0

JDBC , java.sql.Timestamp.

java.sql.Timestamp mysqlDate = new java.sql.Timestamp( javaDate.getTime() );
0

+ Mysql

ResultSet rs=....;

Date tg = new Date(rs.getTimestamp("column datetime").getTime());
SimpleDateFormat sdf = new SimpleDateFormat("dd/MM/yyyy hh:mm aaa");

String val = sdf.format(tg);
0

. /.

java.time

java.time. JDBC-, JDBC 4.2 , java.sql.Time java.time.LocalTime .

java.util.Date UTC. java.time(Instant), , , .

, , .

Instant instant = myJavaUtilDate.toInstant() ;

.

. . , - , "" .

continent/region, America/Montreal, Africa/Casablanca Pacific/Auckland. 3-4 , EST IST, , (!).

ZoneId z = ZoneId.of( "America/Montreal" ) ;  // Or "Asia/Kolkata", or "Pacific/Auckland", etc.
ZonedDateTime zdt = instant.atZone( z ) ;

.

LocalTime lt = zdt.toLocalTime() ;

PreparedStatement, 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() ;

, ResultSet::getObject.

LocalTime lt = myResultSet.getObject( … , LocalTime.class ) ;
0

All Articles