UndefinedReference
UndefinedReference

Reputation: 1253

How do I initialize a java.sql.Date variable?

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?

Upvotes: 4

Views: 9106

Answers (2)

soMuchToLearnAndShare
soMuchToLearnAndShare

Reputation: 1035

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

Upvotes: 0

Elliott Frisch
Elliott Frisch

Reputation: 201437

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());

Upvotes: 4

Related Questions