[英]Replace deprecated Java Date to Calendar.set ou GregorianCalendar.set in a static context
I'm working on Android project using Java and Android Studio IDE is warning me Date(int, int, int) is deprecated as of API16, but when I replace it to Calendar.set the build fails as non-static method cannot be referenced in a static context.我正在使用 Java 开发 Android 项目,Android Studio IDE 警告我 Date(int, int, int) 自 API16 起已弃用,但是当我将其替换为 Calendar.set 时,构建失败,因为无法引用非静态方法在静态上下文中。
This method is being called on a date picker onItenSelectedListener that is static正在静态的日期选择器 onItenSelectedListener 上调用此方法
How it can be deprecated if there is no replacement that can be really used?如果没有可以真正使用的替代品,它如何被弃用?
Use LocalDate
from java.time, the modern Java date and time API.使用 java.time 中的
LocalDate
,现代 Java 日期和时间 API。 It's much nicer to work with.和它一起工作要好得多。
int year = 2019;
int month = 10;
int day = 15;
LocalDate date = LocalDate.of(year, month, day);
System.out.println(date);
The output from this snippet is:此代码段的输出是:
2019-10-15
2019-10-15
LocalDate
numbers both years and months the same way humans do, so there's no subtracting funny values to adjust. LocalDate
以与人类相同的方式计算年份和月份,因此无需减去有趣的值进行调整。 If you need a Date
for an API not yet upgraded to java.time, the conversion goes like this:如果您需要一个尚未升级到 java.time 的 API 的
Date
,则转换过程如下:
Instant startOfDay = date.atStartOfDay(ZoneId.systemDefault()).toInstant();
Date oldfashionedDate = DateTimeUtils.toDate(startOfDay);
System.out.println(oldfashionedDate);
Tue Oct 15 00:00:00 CEST 2019
2019 年 10 月 15 日星期二 00:00:00 CEST
The classes Date
, Calendar
and GregorianCalendar
are all poorly designed and all long outdated.类
Date
、 Calendar
和GregorianCalendar
都设计得很差,而且都已经过时了。 So do consider not using them.所以请考虑不使用它们。
java.time works nicely on both older and newer Android devices. java.time 在较旧和较新的 Android 设备上都能很好地工作。 It just requires at least Java 6 .
它只需要至少Java 6 。
Instant
to Date
use Date.from(startOfDay)
.Instant
转换为Date
使用Date.from(startOfDay)
。org.threeten.bp
with subpackages.org.threeten.bp
导入日期和时间类。java.time
was first described. java.time
。java.time
to Java 6 and 7 (ThreeTen for JSR-310). java.time
到 Java 6 和 7 的 backport(ThreeTen for JSR-310)。I solved the problem replacing我解决了更换问题
return new Date(year-1900, month, day)
by经过
GregorianCalendar calendar = new GregorianCalendar(TimeZone.getTimeZone("GMT"));
calendar.set(year, month-1, day);
return calendar.getTime();
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.