Yottagray
Yottagray

Reputation: 2592

Challenging Java/Groovy Date Manipulation

I have a bunch of dates formatted with the year and week, as follows:

2011-10

The week value is the week of the year(so 1-52). From this week value, I need to output something like the following:

Mar 7

Explicitly, I need the Month that the given week is in, and the date of the first Monday of that week. So in other words it is saying that the 10th week of the year is the week of March 7th.

I am using Groovy. What kind of date manipulation can I do to get this to work?

Upvotes: 2

Views: 1521

Answers (4)

ataylor
ataylor

Reputation: 66099

Here's a groovy solution:

use(groovy.time.TimeCategory) {
    def (y, w) = "2011-10".tokenize("-")
    w = ((w as int) + 1) as String
    def d = Date.parse("yyyy-w", "$y-$w") + 1.day
    println d.format("MMM dd")
}

Upvotes: 1

Adam
Adam

Reputation: 5070

You can use SimpleDateFormat, just like in java. See groovyconsole.appspot.com/script/439001

java.text.DateFormat df = new java.text.SimpleDateFormat('yyyy-w', new Locale('yourlocale'))
Date date = df.parse('2011-10')

To add a week, simply use Date date = df.parse('2011-10')+7

You don't need to set the Locale if your default Locale is using Monday as the first day of week.

Upvotes: 1

Tomasz Nurkiewicz
Tomasz Nurkiewicz

Reputation: 340883

Date date = new SimpleDateFormat("yyyy-w", Locale.UK).parse("2011-10");
System.out.println(new SimpleDateFormat("MMM d").format(date));

The first line returns first day of the 10th week in British Locale (March 7th). When Locale is not enforced, the results are dependent on default JVM Locale.

Formats are explained here.

Upvotes: 1

Sam Barnum
Sam Barnum

Reputation: 10724

Use a GregorianCalendar (or Joda, if you don't mind a dependency)

    String date = "2011-10";
    String[] parts = date.split("-");
    Calendar cal = Calendar.getInstance();
    cal.set(Calendar.YEAR, Integer.parseInt(parts[0]));
    cal.set(Calendar.DAY_OF_WEEK, Calendar.MONDAY);
    cal.set(Calendar.WEEK_OF_YEAR, Integer.parseInt(parts[1])+1);
    DateFormat df = new SimpleDateFormat("MMM d");
    System.out.println(df.format(cal.getTime()) + " (" + cal.getTime() + ")");

EDIT: Added +1 to week, since calendar uses zero-based week numbers

Upvotes: 1

Related Questions