Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I set a full date & time sql using java, and not just the date?

Tags:

I am trying to set a timestamp in my database using java, however in my table all I get is the date, and no time (i.e., looks like "2010-09-09 00:00:00").

I am using a datetime field on my mysql database (because it appears that datetime is more common than timestamp). My code to set the date looks like this:

PreparedStatement ps = conn.prepareStatement("INSERT INTO mytable (datetime_field) VALUES (?)") java.util.Date today = new java.util.Date(); java.sql.Date timestamp = new java.sql.Date(today.getTime()); ps.setDate(1, timestamp); ps.executeUpdate(); 

How do I set the date to include the time?

Edit: I changed the code as per below, and it sets both the date and the time.

PreparedStatement ps = conn.prepareStatement("INSERT INTO mytable (datetime_field) VALUES (?)") java.util.Date today = new java.util.Date(); java.sql.Timestamp timestamp = new java.sql.Timestamp(today.getTime()); ps.setTimestamp(1, timestamp); ps.executeUpdate(); 
like image 661
Adam Morris Avatar asked Sep 09 '10 14:09

Adam Morris


People also ask

How do I format a full date?

The United States is one of the few countries that use “mm-dd-yyyy” as their date format–which is very very unique! The day is written first and the year last in most countries (dd-mm-yyyy) and some nations, such as Iran, Korea, and China, write the year first and the day last (yyyy-mm-dd).

How do I keep a full date in Excel?

Select the cells you want to format. Press CTRL+1. In the Format Cells box, click the Number tab. In the Category list, click Date, and then choose a date format you want in Type.

How do you change a short date to a long date?

From the Start menu, choose Control Panel, or Settings and then Control Panel. From the Control Panel's Classic View, double-click Regional and Language Options. From the Control Panel's Category View, click Clock, Language, and Region, and then Change the date, time, or number format.


1 Answers

Use java.sql.Timestamp and setTimestamp(int, Timestamp). java.sql.Date is date-only, regardless of the type of the column it's being stored in.

like image 82
ColinD Avatar answered Sep 20 '22 17:09

ColinD