及时更改格式并正确保存

时间:2013-11-19 14:56:10

标签: grails simpledateformat

我正在尝试在我的域中以HH:MM格式保存时间但我一直收到错误:

我的域名:

Date startTime
Date endTime

我也尝试过使用DateTime

我的控制器:

def save() {

    def ScheduleMain = new ScheduleMain(params)
        //Storing the weeks instances inside an object  def weeks = ScheduleMain.schedules      //check save yes or no rediect  if (!ScheduleMain.save(flush:true)) {       //render("did not save")        render(view: "create", model: [scheduleInstance: ScheduleMain])         return  }       //set up week count     def weekNo = 0      //building up each instance of data - looping each set of week data     weeks.each() {  //setting up a string to access the schedule data from the params for each week     String schedule = "schedules[" + weekNo + "]"
    //sets up an object that stores this weeks data         def scheduleSave = it
        //loop through each schedules data      params.entrySet().findAll {             it.key == schedule          }.each {
                //set up object to allow access to this schedules data      def schedParam = it.value       println ("This is the value of the new param: " + it.value)         println("Weeks Data: " + scheduleSave)
            //loops through each schedules day          it.value.findAll {
        it.key.startsWith('day_')
        }.each {

            //check to see if day_ object is checked - this cascade saves the day_ data
            if(it.value != null){

                 //set up day string e.g. day_Monday
                 String day = it.key
                 //generate a string based on the day string but stripping stripping out day_ e.g. Monday
                 def daySubString = day[4..-1]
                 //builds up string to access the number of messages for the day
                 String noOfMessages = daySubString + "numberOfMessages"
                 //get value of message that day
                 def noOfMessagesValue = schedParam.get(noOfMessages)


                 scheduleSave = scheduleSave
                 .addToScheduleDays(new ScheduleDays(day:daySubString, 
                    startTime: params.startTime().format('HH:mm'), 
                    endTime: params.endTime().format('HH:mm'), 
                    numberOfMessages: noOfMessagesValue))
                 .save(flush:true)
                }

            }

        }

        weekNo++            }       }

你会看到我循环每次迭代但是在将startTime和endTime保存到域时我得到了错误。希望这对我正在尝试做的事情有意义。

1 个答案:

答案 0 :(得分:0)

  

错误:属性计划[0] .startTime必须是有效的日期

错误有效,因为params包含您的时间的String对象。所以你需要将它解析为日期对象:

scheduleSave = scheduleSave
                 .addToScheduleDays(new ScheduleDays(day:daySubString, 
                    startTime: Date.parse( "HH:mm", params.startTime ).format('HH:mm'), 
                    endTime: Date.parse( "HH:mm", params.endTime ).format('HH:mm') , 
                    numberOfMessages: noOfMessagesValue))
                 .save(flush:true)
                }