Convert java.util.date to java.sql.Date

Asked

Viewed 442 times

3

With this line of code I can get through java.util.Date for java.sql.Date?

java.sql.Date sqlDate = java.sql.Date.valueOf(String.valueOf(date));

Taking into account that date this format :

Sat Jul 01 00:00:00 GMT+01:00 2017
  • date is type java.util.Date?

  • Yes it is , but ta giving me an error maybe it is where I am using this parameter this variable sqlDate, that this with problems.

1 answer

1


If the variable date is a guy java.util.Date, just need:

java.sql.Date sqlDate = new java.sql.Date(date.getTime());

Now if you are going to convert a date in string to sql.Date, will only be possible if it is in format yyyy-[m]m-[d]d, where the month and day may contain only one digit if the second digit is zero, as in 2017-05-01, that can be passed as 2017-5-1.

However, if possible, I recommend using Joda Time making operations with dates and periods in time more flexible.

Reference:

  • That date.getTime() will pass it to dd-mm-yyyy?

  • @Pedrogouveia, no, it returns a millisecond date representation of the type long, which is the range from 1 January 1970 to 00:00:00 until the variable date.

  • How can I make so that instead of sqlDate stay, imagine 2017-01-01 stay 01-01-2017 ?

  • There is no way, sesse format is standard of most databases for date column. Then you need to check your database and see if you have something like this.

  • My database has in dd-mm-yyyy format because I think that’s the normal format to show users

  • @Pedrogouveia your users access your database directly? Because what is usually done is to save in this standard format and when recovering the date via query, format it to dd/mm/yyyy before presenting to the user.

  • Downvoter, if the vote was for some problem in the answer, please inform, otherwise it is no use to negative if the error continues, because I did not notice any error in the answer.

  • I gave upVote I put right !

Show 3 more comments

Browser other questions tagged

You are not signed in. Login or sign up in order to post.