Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Convert datetime in to date

How do I convert a datetime field in Grails to just date, with out capturing the time? I need to do this for comparison with system date.

class Trip 
{
    String name
    String city
    Date startDate
    Date endDate
    String purpose
    String notes

    static constraints = {
        name(maxLength: 50, blank: false)
        startDate(validator: {return (it >= new Date())}) // This won't work as it compares the time as well 
        city(maxLength: 30, blank: false)
    }
}
like image 854
Omnipotent Avatar asked Dec 08 '08 11:12

Omnipotent


People also ask

How do I convert datetime to date in Excel?

The following formula will help you converting date/time format cell to date only in Excel. 1. Select a blank cell you will place the date value, then enter formula =MONTH(A2) & "/" & DAY(A2) & "/" & YEAR(A2) into the formula bar and press the Enter key.

How do you convert datetime to mm dd yyyy?

For the data load to convert the date to 'yyyymmdd' format, I will use CONVERT(CHAR(8), TheDate, 112). Format 112 is the ISO standard for yyyymmdd.


2 Answers

There's [unfortunately] not an "out-of-the box" method for performing this operation in Grails|Groovy|Java.

Somebody always throws in Joda-Time any time a java.util.Date or java.util.Calendar question is raised, but including yet another library is not always an option.

Most recently, for a similar problem, we created a DateTimeUtil class with static methods and something like the following to get a Date only:

class DateTimeUtil {

    // ...

    public static Date getToday() {
        return setMidnight(new Date())
    }

    public static Date getTomorrow() {
        return (getToday() + 1) as Date
    }

    public static Date setMidnight(Date theDate) {
        Calendar cal = Calendar.getInstance()
        cal.setTime(theDate)
        cal.set(Calendar.HOUR_OF_DAY, 0)
        cal.set(Calendar.MINUTE, 0)
        cal.set(Calendar.SECOND, 0)
        cal.set(Calendar.MILLISECOND, 0)
        cal.getTime()
    }

    //...

}

Then, in the validator, you can use

startDate(validator: {return (it.after(DateTimeUtil.today))}) //Groovy-ism - today implicitly invokes `getToday()` 
like image 188
Ken Gentle Avatar answered Oct 06 '22 00:10

Ken Gentle


I cracked it :

startDate(validator: {return (it >= new Date()-1)})

It was that simple ;-)

To change the view in GSP page:

<g:datePicker name="startDate" value="${trip?.startDate}" years="${years}"  precision="day" />

Thanks everyone for the contribution

like image 20
Omnipotent Avatar answered Oct 06 '22 02:10

Omnipotent