关于Date(int, int, int)‘ is deprecated的处理解决方法

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

以上代码在idea中会冒出上面的提示"Date(int, int, int)' is deprecated"

 官方的意思是建议大家少用。但并不是不能用,可以看到在13年前就划掉了。

替代方案有三种:

1,使用Calendar类的set()方法设置年月日信息,再使用getTime()方法将Calendar对象转换为Date对象。

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

2,使用LocalDate类的of()方法创建LocalDate对象,再使用atStartOfDay()方法将其转换为LocalDateTime对象,最后使用toInstant()方法将其转换为Date对象

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

3,使用SimpleDateFormat类将字符串类型的日期转换为Date对象

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

总结:

实际情况是这个官方早在10几年以前就划掉了,不建议再使用,但是一直都提供,你仍然可以使用,也不会有任何问题和后遗症。只是基于优化性能的方面考虑建议用JAVA8的 LocalDate类或者JAVA7以后的Calendar类来实现,实际上写起来最爽的还是最原始的,要将int,int,int转成Date再转成yyyy-MM-dd字符串可以用以下一行代码完成:

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

猜你喜欢

转载自blog.csdn.net/wh445306/article/details/130218815
int