0

I'm having an issue while trying to insert a date into an SQL server using Java:

//final String input = "20120823151034";
final String input = "06282013143533";

final DateFormat df = new SimpleDateFormat("MMddyyyyHHmmss");
final Calendar c = Calendar.getInstance();
c.setTime(df.parse(input));
//c.add(Calendar.MILLISECOND, 1);
String s=df.format(c.getTime());
java.util.Date parsedUtilDate = df.parse(s);  
java.sql.Date sqltDate= new java.sql.Date(parsedUtilDate.getTime());  
System.out.println(sqltDate);

Here, I'm expecting the complete string being output as the year, month, day, hour, minutes, and seconds to be inserted into SQL server, but I'm only getting the year, month, and the date. What should I do to insert the date and the time into the database?

Bill the Lizard
  • 398,270
  • 210
  • 566
  • 880
user2335416
  • 311
  • 2
  • 4
  • 11
  • 1
    why are you converting string->calendar->string->date->....whats the point? also does c.setTime(df.parse(input)); work after making it final? – Bhavik Shah Jul 01 '13 at 13:13
  • here the requirement is i will be given a date with 06282013143533 i have to insert it into sqlserver db so iam trying to convert the date given to sql server compatible!! – user2335416 Jul 01 '13 at 13:18

2 Answers2

4

check your DATA type in database either it should be Timestamp or Datetimefor this purpose you can use database function NOW() for current date and time.and convert your date into timestamp

  Timestamp timestamp = new Timestamp(new Date().getTime());

and insert this timestamp into database

KhAn SaAb
  • 5,248
  • 5
  • 31
  • 52
1

java.sql.Date can be used to store only the year, month and day of the month. It can't be used to store the time of the day.

In order to store time, you would have to use Timestamp. In your above code, replace

java.sql.Date sqltDate= new java.sql.Date(parsedUtilDate.getTime()); 

by

java.sql.Timestamp timestamp = new java.sql.Timestamp(parsedUtilDate.getTime());

The above changes will make things work fine.

Rahul Bobhate
  • 4,892
  • 3
  • 25
  • 48