Groovy/Grails日期课程 - 获取每月的日期

kno*_*orv 9 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 uses year, month, day, hour and minute goes here
Run Code Online (Sandbox Code Playgroud)

Using getAt(Calendar.DAY_OF_MONTH) for the day of the month seems a bit inconsistent in this context. Is there any shorter way to obtain the day of the month?

Joh*_*ner 11

如果您在代码中添加以下内容,则应将该月的日期指定为整数日:

Integer day = now.date
Run Code Online (Sandbox Code Playgroud)

这是一个独立的例子:

def now = Date.parse("yyyy-MM-dd", "2009-09-15")
assert 15 == now.date
Run Code Online (Sandbox Code Playgroud)

  • 也许你错过了它因为可怕的API! (3认同)

Myk*_*yev 7

是不是所有那些线都是垃圾?以下两行在groovysh中完成了这项工作

date = new Date()
date.getAt(Calendar.DAY_OF_MONTH)
Run Code Online (Sandbox Code Playgroud)

要在真实代码而不是控制台中使用它

def date = new Date()
def dayOfMonth = date.getAt(Calendar.DAY_OF_MONTH)
Run Code Online (Sandbox Code Playgroud)