HiveBrain v1.2.0
Get Started
← Back to all entries
patternjavaMinor

Getting all the UTC "day stamps" between 2 dates

Submitted by: @import:stackexchange-codereview··
0
Viewed 0 times
theallutcdatesgettingbetweenstampsday

Problem

I need to get every UTC day stamp in yyyy-MM-dd format (e.g. "2015-07-02") between any two arbitrary Date fields.

My first attempt is this:

public static Set getUTCDayStringsBetween(Date startDt, Date endDt) {
    if (!startDt.before(endDt)) {
        throw new IllegalArgumentException("Start date (" + startDt + ") must be before end date (" + endDt + ")");
    }
    final TimeZone UTC = TimeZone.getTimeZone("UTC");
    final Calendar c = Calendar.getInstance();
    final SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
    sdf.setTimeZone(UTC);
    final Set dayStrings = new LinkedHashSet<>();

    c.setTime(startDt);        
    while (true) {
        dayStrings.add(sdf.format(c.getTime()));
        c.add(Calendar.DATE, 1);//add 1 day                    
        if (c.getTime().after(endDt)) {
            //reached the end of our range. set time to the endDt and get the final day string
            c.setTime(endDt);
            dayStrings.add(sdf.format(c.getTime()));
            break;
        }
    }
    return dayStrings;
}


It seems to work, but I'm wondering if there is a more efficient way to do it (aside from using external time libraries like Joda.).
Also, is there anything I'm glossing over in terms of handling time zones and day-light-savings changes appropriately.

Solution

Instead of an infinite while loop + an if to break out, it would be more natural to convert this to a do-while loop.

The comment "//reached the end of our range. set time to the endDt and get the final day string" is pointless, it just says the same thing with words that the code already tells us perfectly clearly.

c is not a great name for a Calendar. How about cal, or even calendar ? Instead of startDt and endDt, I would just also them out.

It's a bit smelly about the interface that the method requires the date parameters in a specific order, but this is not obvious from the name. And if the caller uses the wrong order, the runtime exception is a heavy penalty, crashing the application. It's not great to have rules that cannot be enforced at compile time, but I don't have a good counter proposal for you.

Context

StackExchange Code Review Q#95587, answer score: 3

Revisions (0)

No revisions yet.