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?

2
  • 1
    why are you converting string->calendar->string->date->....whats the point? also does c.setTime(df.parse(input)); work after making it final? Commented Jul 1, 2013 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!! Commented Jul 1, 2013 at 13:18

2 Answers 2

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

Sign up to request clarification or add additional context in comments.

2 Comments

could you please tell me how to get that,its not for current date and time it should be applicable to previous dates also
convert your date string to date then convert it to date then timestamp insert it.
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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.