简体   繁体   中英

Grails insert date without time

I have a date attribute in my domain and I want to insert to MySQL without time. getting exception cannot cast string to date.Exception message:

Cannot cast object 2013-03-09 with class java.lang.String to class java.util.Date

I want to insert to the database without time.

Domain:

class Day {

    
Date date
    
        static mappings = {
        table name:'Days'
   
              date type: 'date'
         
         
    }

Controller:

def today = new Date()
def ymdFmt = new java.text.SimpleDateFormat("yyyy-MM-dd")
Date dateYmd = ymdFmt.format(today) 



        day.date =dateYmd 
day.date = new Date().clearTime()

clearTime() 将时间部分重置为 00:00:00

I think you wan't to look at Date.parse http://groovy.codehaus.org/groovy-jdk/java/util/Date.html#parse(java.lang.String , java.lang.String)

You can parse the date like.

String stringDate = '28/09/2010'
Date date = new Date().parse('d/M/yyyy', stringDate)

You should use java.sql.Date instead of java.util.Date .

The java.sql.Date class corresponds to SQL DATE which means it stores years, months and days while hour, minute, second and millisecond are ignored. Additionally java.sql.Date isn't tied to timezones.

For a good explanation about the two see java.util.Date vs java.sql.Date

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM