Best way to determine Java constant dates

I want to define some constants, in particular the date and calendar, which may exist before my domain. I have code that works, but its ugly. I am looking for suggestions for improvement.

 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 appoint them July 4, 1776. I would prefer not to have a "working" variable at all.

thanks

+4
source share
3 answers

I'm not sure I understand ... but doesn't that 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(); 
+4
source

I will extract it into the method (in the util class, assuming other classes want this too):

 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 just

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

It might be better to use XML string notation. This is more human readable and also avoids the local variable that you would like to eliminate:

 import javax.xml.bind.DatatypeConverter; Date theDate = DatatypeConverter.parseDateTime("1776-06-04T00:00:00-05:00").getTime() 
+1
source

Source: https://habr.com/ru/post/1379061/


All Articles