tags:

views:

1045

answers:

4

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?

+1  A: 

Isn't all those lines are kind of garbage? The following two lines do the job in a groovysh

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

To use this at your real code and not in the console

def date = new Date()
def dayOfMonth = date.getAt(Calendar.DAY_OF_MONTH)
Mykola Golubyev
Is that an answer?
knorv
This code gives me 6 at the groovysh console. If it is what you want than this is the answer.
Mykola Golubyev
The problem is not obtaining the day of the month. The problem is doing it in a consistent way.
knorv
+2  A: 

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.

Jared
A: 

This version is fairly terse:

Calendar.instance.get(Calendar.DAY_OF_MONTH)
Burt Beckwith
Absolutely, but compare it to the other lines. I was looking for a consistent way to do it.
knorv
+3  A: 

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
John Wagenleitner
Thanks! I don't know how I could miss it!
knorv