Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Set Date in a single line

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

like image 594
hibernate Avatar asked May 20 '10 20:05

hibernate


People also ask

How do you initialize a date?

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.

How do I change date format in SimpleDateFormat?

You can just use: Date yourDate = new Date(); SimpleDateFormat DATE_FORMAT = new SimpleDateFormat("yyyy-MM-dd"); String date = DATE_FORMAT. format(yourDate);


2 Answers

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.

like image 152
aioobe Avatar answered Oct 20 '22 21:10

aioobe


You could use

new SimpleDateFormat( "yyyyMMdd" ).parse( "20100520" ) 
like image 21
tangens Avatar answered Oct 20 '22 20:10

tangens