Better logic for date grouping