Groovy/Grails日期类-获取月份的日期

Groovy/Grails日期类-获取月份的日期,grails,groovy,Grails,Groovy,目前,我使用以下代码在Groovy中获取年、月、月日、小时和分钟: Date now = new Date() Integer year = now.year + 1900 Integer month = now.month + 1 Integer day = now.getAt(Calendar.DAY_OF_MONTH) // inconsistent! Integer hour = now.hours Integer minute = now.minutes // Code that us

目前,我使用以下代码在Groovy中获取年、月、月日、小时和分钟:

Date now = new Date()
Integer year = now.year + 1900
Integer month = now.month + 1
Integer day = now.getAt(Calendar.DAY_OF_MONTH) // inconsistent!
Integer hour = now.hours
Integer minute = now.minutes
// Code that uses year, month, day, hour and minute goes here

在这种情况下,使用
getAt(Calendar.DAY\u OF\u MONTH)
作为月日似乎有点不一致。有没有更短的方法来获取月日

这些台词不是都是垃圾吗? 下面两行代码在groovysh中完成了这项工作

date = new Date()
date.getAt(Calendar.DAY_OF_MONTH)
要在真实代码中使用它,而不是在控制台中使用它

def date = new Date()
def dayOfMonth = date.getAt(Calendar.DAY_OF_MONTH)

你这样做是唯一的办法。JavaDate对象存储月份和日期,但不存储任何信息,例如给定月份的长度或您所在月份的哪一天。您需要使用Calendar类来查找大量此类信息。

此版本相当简洁:

Calendar.instance.get(Calendar.DAY_OF_MONTH)

如果将以下内容添加到代码中,则应将月份的日期指定给日期整数:

Integer day = now.date
以下是一个独立的示例:

def now = Date.parse("yyyy-MM-dd", "2009-09-15")
assert 15 == now.date

在Groovy中,您可以通过
日期
获得每月的某一天,如下所示:

​Date date = new Date()
int dayOfMonth = date[Calendar.DAY_OF_MONTH]

你为什么现在这样做。年+1900?Mykola:new Date()。年目前是109,因此需要添加1900。但是为什么你要将它添加到某个“年”中而不使用它?年、月、日、小时和分钟在代码中稍后使用。毫秒或微秒呢?我现在尝试了。毫秒或微秒,但没有这样的属性。这段代码在groovysh控制台上为我提供了6。如果这是你想要的,那么这就是答案。问题是没有得到一个月的哪一天。“垃圾”实际上是问题的上下文,但将其与其他行进行比较。我一直在寻找一种始终如一的方法。谢谢!我不知道我怎么会错过它!也许你错过它是因为可怕的API!