将日期时间转换为日期

将日期时间转换为日期

本文介绍了将日期时间转换为日期的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何将Grails中的datetime字段转换为日期,并捕获时间?我需要这样做,以便与系统日期进行比较。

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)
    }
}


推荐答案

有[不幸的是] -o-the-box方法在 Grails | Groovy | Java 中执行此操作。

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

有人始终随时会在中抛出 java.util 。日期 java.util.Calendar 提出问题,但包括另一个库并不总是一个选项。

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.

最近,对于类似的问题,我们创建了一个 DateTimeUtil 类与 static 方法和类似以下内容获取 Date only:

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()`

这篇关于将日期时间转换为日期的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-11 22:46