Alex Rivera | Logout

Groovy/Grails date class - getting day of month

Asked 2009-09-06T13:28:13.557
9

Currently I'm using the following code to get year, month, day of month, hour and minute in 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

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?

Edit
Report

2 Answers

12

If you add the following to your code it should assign the day of the month to the day Integer:

Integer day = now.date

Here's a stand-alone example:

def now = Date.parse("yyyy-MM-dd", "2009-09-15")
assert 15 == now.date
answered 2009-09-06T17:35:18.933
2

The way you are doing it is the only way. The java date object stores the month and day, but doesn't store any information such as how long the given month is or what day of the month your on. You need to use the Calendar class to find out a lot of this info.

answered 2009-09-06T13:53:31.187

Your Answer