Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Date to Day of Week in Groovy

Tags:

date

groovy

I have variables that are formatted like the following example:

2011-03-07

and from them I want to output the day of the week. For example:

Monday

or even just

Mon

I am working in Groovy, any ideas?

like image 345
Yottagray Avatar asked Mar 07 '11 22:03

Yottagray


2 Answers

You can use Date.parse to turn the string into a date, and then index it with Calendar.DAY_OF_WEEK to get the specific day. Example:

assert Date.parse("yyyy-MM-dd", "2011-03-07")[Calendar.DAY_OF_WEEK] == Calendar.MONDAY

If you want the day as a string, try the Date.format method. The exact output depends on your locale:

assert Date.parse("yyyy-MM-dd", "2011-03-07").format("EEE") == "Mon"
assert Date.parse("yyyy-MM-dd", "2011-03-07").format("EEEE") == "Monday"

See the documentation for SimpleDateFormat for more information on the formatting strings.

If you want the day formatted for a specific locale, you'll have to create a SimpleDateFormat object and pass in a locale object.

fmt = new java.text.SimpleDateFormat("EEE", new Locale("fr"))
assert fmt.format(Date.parse("yyyy-MM-dd", "2011-03-07")) == "lun."
fmt = new java.text.SimpleDateFormat("EEEE", new Locale("fr"))
assert fmt.format(Date.parse("yyyy-MM-dd", "2011-03-07")) == "lundi"
like image 130
ataylor Avatar answered Sep 20 '22 08:09

ataylor


new SimpleDateFormat('E').format Date.parse("10-jan-2010")

neater for me

like image 25
han Avatar answered Sep 17 '22 08:09

han