Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Groovy/Grails date class - getting day of month

Tags:

grails

groovy

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?

like image 895
knorv Avatar asked Sep 06 '09 13:09

knorv


2 Answers

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
like image 57
John Wagenleitner Avatar answered Oct 10 '22 14:10

John Wagenleitner


You can get just the day of the month from a Date in Groovy like this:

​Date date = new Date()
int dayOfMonth = date[Calendar.DAY_OF_MONTH]
like image 33
Jim Chertkov Avatar answered Oct 10 '22 12:10

Jim Chertkov