【发布时间】:2012-06-02 05:50:50
【问题描述】:
我正在尝试将字符串格式的日期与当前日期进行比较。这就是我的做法(尚未测试,但应该可以),但我使用的是不推荐使用的方法。有什么好的替代方案吗?谢谢。
附:我真的很讨厌用 Java 做 Date 的东西。有很多方法可以做同样的事情,你真的不确定哪一种是正确的,因此我的问题在这里。
String valid_until = "1/1/1990";
Calendar cal = Calendar.getInstance();
SimpleDateFormat sdf = new SimpleDateFormat("dd/mm/yyyy");
Date strDate = sdf.parse(valid_until);
int year = strDate.getYear(); // this is deprecated
int month = strDate.getMonth() // this is deprecated
int day = strDate.getDay(); // this is deprecated
Calendar validDate = Calendar.getInstance();
validDate.set(year, month, day);
Calendar currentDate = Calendar.getInstance();
if (currentDate.after(validDate)) {
catalog_outdated = 1;
}
【问题讨论】:
-
在 2018 年,最好的方法不涉及
Calendar、SimpleDateFormat、Date或任何其他早已过时的 Java 日期和时间类。而是使用java.time, the modern Java date and time API。是的,您可以在 Android 上使用它。对于较旧的 Android,请参阅 How to use ThreeTenABP in Android Project。