Date of the Day of the Week at Groovy

I have variables that are formatted as follows:

2011-03-07 

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

 Monday 

or even just

 Mon 

I work in Groovy, any ideas?

+7
source share
3 answers

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

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

If you want the day to be a string, try the Date.format method. The exact result depends on your language:

 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 formatting strings.

If you need a day formatted for a specific locale, you will need to create a SimpleDateFormat object and pass in the 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" 
+19
source
 new SimpleDateFormat('E').format new SimpleDateFormat('yyyy-MM-dd').parse('2011-03-07') 
0
source
 new SimpleDateFormat('E').format Date.parse("10-jan-2010") 

neater for me

0
source

All Articles