Reputation: 2378
I'm working on a java component that tags events with a date window for aggregating metrics by day, week, month, and so forth.
Mapping from a date to its aggregate category is straightforward - just format as a String
using an appropriate pattern for the desired window. For example, a date could be mapped to month-level aggregation with the Formatter
pattern "%1$04tY-%1$02tm"
(i.e., YYYY-MM
).
My problem is reverse-mapping from the window to its bounding dates, e.g. from the aggregate month 2012-02
to its bounding dates 2012-02-01
and 2012-03-01
(using half-open intervals). I need this to effectively tag entire spans of dates in my data store (MongoDB) with a single statement (this example omits ISODate(…)
for clarity):
db['events'].update(
{eventDate: {$gte: "2012-02-01", $lt: "2012-03-01"},
{$set: {month: "2012-02"}
);
I came across Joda-Time and suspect that its Partial
API might support this functionality. I'm trying to teach myself, but does anyone already know how to do this?
Upvotes: 0
Views: 932
Reputation: 6509
Joda-Time is definitely the way to go for this.
Depending on what you want to do with TimeZones, the following shows what I think you want.
YearMonth ym = new YearMonth(2012, DateTimeConstants.MARCH);
Interval interval = ym.toInterval();
LocalDate monthStart = interval.getStart().toLocalDate();
LocalDate monthEnd = interval.getEnd().toLocalDate();
System.out.println("Start:" + monthStart);
System.out.println("End: " + monthEnd);
Note: This requires at least Joda-Time v2.0
Upvotes: 1
Reputation: 30088
I'd suggest using http://joda-time.sourceforge.net/api-release/org/joda/time/LocalDate.html
You can construct the lower bound by parsing the year and the month from the window, and then
LocalDate lowerBound = new LocalDate(year, month, 1)
Then, the upper bound is
LocalDate upperBound = lowerBound.plusMonths(1)
Upvotes: 0