2

I have a problem in java with sql date. I have the value of year-y, month-m,day-d I create new Date(y,m,d) but it says that this constructor is deprecated and it returns wrong date, how can I correctly set date, having y,m,d ?

6 Answers 6

5

According to the API,

As of JDK version 1.1, replaced by Calendar.set(year + 1900, month, date) or GregorianCalendar(year + 1900, month, date).

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

2 Comments

can i change the value of year ?
@Vahan: Calendar.set(Calendar.YEAR, year + 1900) is this what you mean? I'm a little confused...
1

You should use public Date(long date) where date is the number of milliseconds since January 1, 1970, 00:00:00 GMT

In your case you can also use:

Date mydate = Date.valueOf("2011-05-04"); // yyyy-mm-dd

1 Comment

how can i get long Date, having year, month day ?
1

Here's how you can convert between the two:

new java.util.Date(sqlDate.getTime());

Comments

1
Calendar c = Calendar.getInstance();
c.set(year, month, date);

Date d = c.getTime();

1 Comment

in this case cannot convert from java.util.date to sql.date
1

Use Calendar.

Calendar c = Calendar.getInstance();
c.set(Calendar.DAY_OF_MONTH, d);
c.set(Calendar.MONTH, m);
c.set(Calendar.YEAR, y);

Then if you have to use dates, then you can do the following -

Date d = c.getTime();

1 Comment

in this case cannot convert from java.util.date to sql.date
1

Use the Calendar class:

  Calendar cal = Calendar.getInstance();
    cal.set(year, month, date);
    java.sql.Date date = new java.sql.Date(cal.getTimeInMillis());

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.