Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

like image 957
fishtoprecords Avatar asked Nov 01 '11 01:11

fishtoprecords


People also ask

How do you declare a constant date in Java?

To make any variable a constant, we must use 'static' and 'final' modifiers in the following manner: Syntax to assign a constant value in java: static final datatype identifier_name = constant; The static modifier causes the variable to be available without an instance of it's defining class being loaded.

How do you manage a constant in Java?

If constants are logically related to a class, we can just define them there. If we view a set of constants as members of an enumerated type, we can use an enum to define them. In our example, we've defined a constant for UPPER_LIMIT that we're only planning on using in the Calculator class, so we've set it to private.

How do you name a constant in Java?

The names of variables declared class constants and of ANSI constants should be all uppercase with words separated by underscores ("_"). (ANSI constants should be avoided, for ease of debugging.)

How do you set a specific date in Java?

The setTime() method of Java Date class sets a date object. It sets date object to represent time milliseconds after January 1, 1970 00:00:00 GMT. Parameters: The function accepts a single parameter time which specifies the number of milliseconds. Return Value: It method has no return value.


2 Answers

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();
like image 140
Dave L. Avatar answered Sep 21 '22 23:09

Dave L.


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);
like image 38
avh4 Avatar answered Sep 19 '22 23:09

avh4