Converting java.util.Date to java.sql.Date resulting in date changes [duplicate]

て烟熏妆下的殇ゞ 提交于 2021-01-29 09:11:49

问题


I was having some problem when trying to convert java.util.Date to java.sql.Date. My date parameter passed in was originally a string in this format: 2019-01-31. Then I am trying to convert it to java.util.date using this code:

    SimpleDateFormat formatter = new SimpleDateFormat("YYYY-MM-DD");
    Date date = null;
    try {
        date =  formatter.parse(this._dDate);
    } catch (ParseException e) {
        e.printStackTrace();
    }

In my SQL statement, I am trying to convert it to java.sql.Date:

buffer.append("SELECT * FROM TABLE1 WHERE LAST_LOGIN_DT < ");
buffer.append("TO_DATE('" + new java.sql.Date(date.getTime()) + "','YYYY-MM-DD') ");

However, when I printed out the buffer in string, I realized that the date is changed. For instance, the data string I passed in is 2018-01-01, but in the SQL statement it became 2017-12-31. Any ideas?

Thanks!


回答1:


Let's take a look at following example first:

String date = "2018-01-01";

SimpleDateFormat sdf1 = new SimpleDateFormat("YYYY-MM-DD");
System.out.println(sdf1.parse(date));
System.out.println(sdf1.parse(date).getYear());
System.out.println(sdf1.parse(date).getMonth());
System.out.println(sdf1.parse(date).getDay());

SimpleDateFormat sdf2 = new SimpleDateFormat("yyyy-MM-dd");
System.out.println(sdf2.parse(date));
System.out.println(sdf2.parse(date).getYear());
System.out.println(sdf2.parse(date).getMonth());
System.out.println(sdf2.parse(date).getDay());

Console output:

Sun Dec 31 00:00:00 CST 2017
117
11
0
Mon Jan 01 00:00:00 CST 2018
118
0
1

Now I think you have already noticed the difference!
Quoted from Class SimpleDateFormat:

Y means Week year and D means Day in year.
y means Year and d means Day in month.

yyyy and YYYY both represent a year but yyyy represents the calendar year while YYYY represents the year of the week. And, dd represents the calendar day while DD represents the day of the month. Therefore, there are 2 ways to fix your issue:

Method 1
Change the format for SimpleDateFormat from YYYY-MM-DD to yyyy-MM-dd if you still want to convert this._dDate to java.util.Date then java.sql.Date, but I strongly recommend you don't do this.

Method 2
The better way is directly using java.sql.Date.valueOf(this._dDate) and the format of this._dDate is supposed to be yyyy-MM-dd.



来源:https://stackoverflow.com/questions/58741021/converting-java-util-date-to-java-sql-date-resulting-in-date-changes

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!