user1407415
user1407415

Reputation: 109

get month Number from month name in groovy

is there a built-in function or API i can use to convert month name like FEB, February to month number 02?

I'm passing from the view to the controller.

Upvotes: 3

Views: 6285

Answers (3)

ataylor
ataylor

Reputation: 66099

Call Date.parse with MMM as the format string. This will give you a Date object which provides access to the month number. Example:

def d = Date.parse('MMM', 'Feb')
def num = d.format('MM') as int
assert num == 2

Upvotes: 8

tim_yates
tim_yates

Reputation: 171154

You can do:

String monthString = 'Feb'

int month = Calendar.instance.with {
  time = new Date().parse( "MMM", monthString )
  it[ MONTH ]
}

// Feb is 1 of course, not 2 as in your question
assert month == 1

Upvotes: 1

hsan
hsan

Reputation: 1559

You can parse month names to dates with the regular parse function of Date:

new Date().parse("MMM", "Feb")

Upvotes: 1

Related Questions