According to the Java API, the constructor Date(year, month, day)
is deprecated. I know that I can replace it with the following code:
Calendar myCal = Calendar.getInstance(); myCal.set(Calendar.YEAR, theYear); myCal.set(Calendar.MONTH, theMonth); myCal.set(Calendar.DAY_OF_MONTH, theDay); Date theDate = myCal.getTime();
However, I would like something shorter to replace it with (ideally one to two lines).
Calendar to initialize date: Calendar calendar = Calendar. getInstance(); //To Initialize Date to current Date Date date = calendar. getTime(); //To Initialize Date to a specific Date of your choice (here I'm initializing the date to 2022-06-15) calendar.
You can just use: Date yourDate = new Date(); SimpleDateFormat DATE_FORMAT = new SimpleDateFormat("yyyy-MM-dd"); String date = DATE_FORMAT. format(yourDate);
You could use new GregorianCalendar(theYear, theMonth, theDay)
.getTime()
:
public GregorianCalendar(int year, int month, int dayOfMonth)
Constructs a GregorianCalendar with the given date set in the default time zone with the default locale.
You could use
new SimpleDateFormat( "yyyyMMdd" ).parse( "20100520" )
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