简体   繁体   中英

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

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);

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();

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()

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM