4

I'm trying to initialize a variable called startDate using java.sql.Date.

I've tried...

java.sql.date startDate = "02/04/2015"

But it thinks it's a string.

java.sql.date startDate = 02/04/2015

But it thinks it's an int.

java.sql.date startDate = 02-04-2015

But it displays the error "invalid character constant".

How do I properly initialize this variable?

1
  • You create it like you would any other object; but, you will need to parse the String value to a java.util.Date and use this to sees an instance of java.sql.Date Commented Feb 5, 2015 at 2:10

2 Answers 2

4

One possible approach is to use a SimpleDateFormat and the java.sql.Date(long) constructor like

DateFormat df = new SimpleDateFormat("MM-dd-yyyy");
java.sql.Date sqlDate = new java.sql.Date(df.parse("02-04-2015").getTime());
Sign up to request clarification or add additional context in comments.

Comments

0

you could also try

java.sql.Date sqlDate = new java.sql.Date(2020,12,12);

I do not know why this is deprecated, but it is very intuitive for me. basically year, month, day integer.

Update: 10 months ago, my further reading told me never use this old API. See here: https://www.linkedin.com/posts/min-shi-schurr-3859468_how-to-effectively-use-dates-and-timestamps-activity-6873395326397558784-2ehr?utm_source=share&utm_medium=member_ios

3 Comments

Attention: The deprecated constructor is not working as expected, to set the year to 2020 you have to give 120 (year value minus 1900). Use the date formatter for better readability and support of clean code.
I have now updated my “answer”
Deleting the Answer would be a better idea (IMO). (What is the point of suggesting an alternative that is deprecated and then giving an incorrect example?)

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.