fishtoprecords
fishtoprecords

Reputation: 2404

Best way to define Java constant dates

I want define some constants, specifically a Date and Calendar that are before my domain can exist. I've got some code that works but its ugly. I am looking for improvement suggestions.

    static Calendar working;
    static {
        working = GregorianCalendar.getInstance();
        working.set(1776, 6, 4, 0, 0, 1);
    }
    public static final Calendar beforeFirstCalendar = working;
    public static final Date beforeFirstDate = working.getTime();

I'm setting them to July 4th, 1776. I'd rather not have the "working" variable at all.

Thanks

Upvotes: 6

Views: 20596

Answers (3)

Rich
Rich

Reputation: 15457

It might be clearer to use the XML string notation. This is more human readable and also avoids the local variable which you wanted to eliminate:

import javax.xml.bind.DatatypeConverter;

Date theDate = DatatypeConverter.parseDateTime("1776-06-04T00:00:00-05:00").getTime()

Upvotes: 2

avh4
avh4

Reputation: 2655

I'd extract it to a method (in a util class, assuming other classes are going to want this as well):

class DateUtils {
  public static Date date(int year, int month, int date) {
    Calendar working = GregorianCalendar.getInstance();
    working.set(year, month, date, 0, 0, 1);
    return working.getTime();
  }
}

Then simply,

public static final Date beforeFirstDate = DateUtils.date(1776, 6, 4);

Upvotes: 5

Dave L.
Dave L.

Reputation: 9781

I'm not sure I understand....but doesn't this work?

public static final Calendar beforeFirstCalendar;
static {
    beforeFirstCalendar = GregorianCalendar.getInstance();
    beforeFirstCalendar.set(1776, 6, 4, 0, 0, 1);
}
public static final Date beforeFirstDate = beforeFirstCalendar.getTime();

Upvotes: 7

Related Questions