About Date(int, int, int)' is deprecated processing solution

// 将日期转换为指定格式的字符串('Date(int, int, int)' is deprecated)
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
String sDate = sdf.format(new Date(year - 1900, month, dayOfMonth));

The above code will pop up the above prompt "Date(int, int, int)' is deprecated" in the idea

 The official meaning is that it is recommended that you use it less. But it's not unusable. It can be seen that it was crossed out 13 years ago.

There are three alternatives:

1. Use the set() method of the Calendar class to set the year, month and day information, and then use the getTime() method to convert the Calendar object to a Date object.

Calendar calendar = Calendar.getInstance();
calendar.set(year, month, dayOfMonth);
SimpleDateFormat sdf1 = new SimpleDateFormat("yyyy-MM-dd");
String sDate1 = sdf1.format(calendar.getTime());

2. Use the of() method of the LocalDate class to create a LocalDate object, then use the atStartOfDay() method to convert it to a LocalDateTime object, and finally use the toInstant() method to convert it to a Date object

LocalDate localDate = LocalDate.of(year, month + 1, dayOfMonth);
LocalDateTime localDateTime = localDate.atStartOfDay();
Date date = Date.from(localDateTime.toInstant(ZoneOffset.ofHours(8)));

3. Use the SimpleDateFormat class to convert the date of the string type to a Date object

String strDate = year + "-" + (month + 1) + "-" + dayOfMonth;
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
Date date = sdf.parse(strDate);

Summarize:

The actual situation is that this official was crossed out as early as 10 years ago, and it is not recommended to use it anymore, but it has been provided all the time, and you can still use it without any problems or sequelae. It is only based on the consideration of optimization performance that it is recommended to use the LocalDate class of JAVA8 or the Calendar class after JAVA7. In fact, it is the most cool to write or the most primitive. It is necessary to convert int, int, and int into Date and then into yyyy-MM The -dd string can be done with the following line of code:

String sDate = new SimpleDateFormat("yyyy-MM-dd").format(new Date(year - 1900, month, dayOfMonth));

Guess you like

Origin blog.csdn.net/wh445306/article/details/130218815