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
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.
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.
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.)
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.
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();
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);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With