2011-07-19 15 views
3

我有一個數據庫表TableA,它有一個'theDate'列,數據庫中的數據類型是DATE。在GORM Grails中保存和查詢日期

當我通過GORM將java.util.Date保存到'theDate'時,通過執行select * from TableA來查看錶中的數據時,它似乎只保存日期值。

然而,當我運行一個查詢,如:

select * from TableA where theDate = :myDate 

沒有結果被發現,但如果我運行類似;

select * from TableA where theDate <= :myDate 

我確實得到了結果。

所以這就像時間是相關的。

我的問題是我如何保存日期和查詢日期忽略時間完全只是匹配在確切的日期?

謝謝。

注意:我也嘗試使用sql.Date和util.Calendar,但沒有成功。

回答

0

我想通了。

我使用DateGroovyMethods.clearTime在保存前清除時間值。

0

您的問題可能是重複的。見Convert datetime in to date。但是如果任何人有更多最新的信息,那就太好了。

如果沒有幫助,您可以按我的方式進行破解,並使用BETWEEN限制,例如,

def today = new Date() 
def ymdFmt = new java.text.SimpleDateFormat("yyyy-MM-dd") 
def dateYmd = ymdFmt.format(today) 
def dateTimeFormat = new java.text.SimpleDateFormat("yyyy-MM-dd hh:mm:ss"); 
def startDate = dateTimeFormat.parse("${dateYmd} 00:00:00"); 
def endDate = dateTimeFormat.parse("${dateYmd} 23:59:59"); 
MyDomain.findAll("from MyDomain where dateCreated between ? and ?", [startDate, endDate]) 

這絕對不美觀,但它可能會讓你去你要去的地方。

7

clearTime()

您可以在保存前使用clearTime()和比較,以零出時間字段前:

// zero the time when saving 
new MyDomain(theDate: new Date().clearTime()).save() 

// zero the target time before comparing 
def now = new Date().clearTime() 
MyDomain.findAll('SELECT * FROM MyDomain WHERE theDate = :myDate', [myDate: now]) 

喬達時間插件

另一種方法是安裝joda-time plugin並使用LocalDate類型(它只能保存日期信息,不會)inst ead的Date。對於它的價值,我認爲我沒有在沒有使用Joda插件的情況下使用日期工作。這完全值得。

+0

我用DateGroovyMethods.clearTime到底。謝謝。 – C0deAttack

1

如果您保存的日期未經清理,您可以使用範圍檢索它,正如Jordan H.編寫的,但以更簡單的方式。

def getResults(Date date) { 

    def from = date.clearTime() 
    def to = from + 1 

    def results = MyDomain.findAll("from MyDomain where dateCreated between :start and :stop" ,[start:from,stop:to]) 

} 
0

您可以使用DB型日期沒有日期時間,在提交類型