Grails - illegal arguments for java.sql.Date

橙三吉。 提交于 2020-01-05 13:09:14

问题


I'm trying to create an sql.Date by creating a Calendar object on the current date. This is driving me crazy, if i hardcode the date as a string every thing is fine:

def dat = java.sql.Date.valueOf("2011-01-31");

But, if I create the same string in code I'm getting an illegal argument error.

def currentDay  = {

    def today = Calendar.getInstance();

    def dateYear = today.get(Calendar.YEAR);
    def dateMonth = today.get(Calendar.MONTH) + 1;
    def dateDay =today.get(Calendar.DATE);

    def todayDate = (dateYear + "-" + dateMonth + "-" + dateDay);
    def todayDateString = todayDate.toString();
    def todayDate2 = java.sql.Date.valueOf(todayDateString);

    [ today : todayDate2 ]
}

Running this is yielding this stacktrace:

java.lang.IllegalArgumentException
    at java.sql.Date.valueOf(Date.java:138)
    at java_sql_Date$valueOf.call(Unknown Source)
    at samma.TapesController$_closure7.doCall(TapesController.groovy:178)
    at samma.TapesController$_closure7.doCall(TapesController.groovy)
    at java.lang.Thread.run(Thread.java:619)

I know I'm doing something completely stupid, but I cannot figure out what, nor what a workaround could be.

Thanks

Donald.


回答1:


Replace all the code above with

def currentDay  = {

    def todayDate = new java.sql.Date(new Date().time)
    todayDate.clearTime()

    [today: todayDate]
}



回答2:


Why are you converting to a string at all? Just make sure your Calendar has the field values that you want, and then call

new java.sql.Date(calendar.getTime().getTime());

Alternatively, given that you just need the millis to be right, I would try to use Joda Time if at all possible - it'll be easier than manipulating a calendar, IMO. You can convert from a Joda Time instant (or whatever) to a long value very easily.




回答3:


java.sql.Date.valueOf(String date) throws an IllegalArgumentException if the date given is not in the JDBC date escape format (yyyy-mm-dd). The date you are providing has the format yyyy-m-dd, (only one digit month for 1-9) therefore it is invalid.

As a workaround, use SimpleDateFormat to get a two digit month or directly work with dates without intermediate String conversion like Jon Skeet suggests.



来源:https://stackoverflow.com/questions/4856545/grails-illegal-arguments-for-java-sql-date

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