Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Datetime in java

Tags:

java

jdbc

I have a JDBC current date and time insert into Mysql Database.

It submits the current date and a fixed time into the Mysql date type field as 2012/05/25 00:00:00. The date part works very fine but the time doesn't shows any value.

I'm inserting the value with the following code:

java.util.Date myDate = new java.util.Date();
java.sql.Date sqlDate = new java.sql.Date(myDate.getTime());
PreparedStatement PStmt = con.prepareStatement(Sql query);
PStmt.setDate(1,sqlDate);
like image 385
Narayan Avatar asked May 25 '12 10:05

Narayan


People also ask

What is the data type for datetime in java?

TIME Type. The time data type. The format is yyyy- MM -dd hh:mm:ss, with both the date and time parts maintained. Mapped to java.

Does java have a datetime?

Java provides the Date class available in java. util package, this class encapsulates the current date and time.

Is datetime a class in Java?

Encapsulates a datetime. The datetime is stored as a timestamp and may be persisted as a timestamp. Creates this by converting the given cal calendar value into timestamp.

What does LocalTime represent in java?

LocalTime is an immutable date-time object that represents a time, often viewed as hour-minute-second. Time is represented to nanosecond precision. For example, the value "13:45.30. 123456789" can be stored in a LocalTime .


2 Answers

Use java.sql.Timestamp instead of java.util.Date

For example if you are using PreparedStatement to handle your insert, you can pass your date as;

java.util.Date date = new Date();
pst.setTimestamp(columIndex, new java.sql.Timestamp(date.getTime()));
like image 169
Bitmap Avatar answered Oct 02 '22 03:10

Bitmap


I think you need to have timestamp as column type in mysql.

like image 36
Subir Kumar Sao Avatar answered Oct 02 '22 01:10

Subir Kumar Sao