[英]Groovy/Grails date class - getting day of month
目前我正在使用以下代码来获取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_OF_MONTH)
表示该月的某一天似乎有点不一致。 有没有更短的方法来获得该月的哪一天?
如果您在代码中添加以下内容,则应将该月的日期指定为整数日:
Integer day = now.date
这是一个独立的例子:
def now = Date.parse("yyyy-MM-dd", "2009-09-15")
assert 15 == now.date
是不是所有那些线都是垃圾? 以下两行在groovysh中完成了这项工作
date = new Date()
date.getAt(Calendar.DAY_OF_MONTH)
要在真实代码而不是控制台中使用它
def date = new Date()
def dayOfMonth = date.getAt(Calendar.DAY_OF_MONTH)
你这样做是唯一的方法。 java日期对象存储月份和日期,但不存储任何信息,例如给定月份的持续时间或月份的当天。 您需要使用Calendar类来查找大量此类信息。
这个版本相当简洁:
Calendar.instance.get(Calendar.DAY_OF_MONTH)
您可以从Groovy中的Date
获取该月的Date
,如下所示:
Date date = new Date()
int dayOfMonth = date[Calendar.DAY_OF_MONTH]
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.