比较日期在Android的最佳途径途径、日期、Android

2023-09-12 07:30:11 作者:Neither candidate 逾期不候

我想在一个字符串格式的日期来比较当前日期。这是我做的(没有测试,但应该工作),但我用德precated方法。任何好的建议的替代?谢谢你。

P.S。我真的很讨厌做日期的东西在Java中。有这么多的方式做同样的事情,那你真的是不知道哪一个是正确的,所以我的问题在这里。

 字符串valid_until =1990年1月1日;

日历CAL = Calendar.getInstance();
SimpleDateFormat的SDF =新的SimpleDateFormat(DD / MM / YYYY);
日期strDate = sdf.parse(valid_until);

INT年= strDate.getYear(); //这是德precated
INT月= strDate.getMonth()//这是德precated
INT天= strDate.getDay(); //这是德precated

日历validDate = Calendar.getInstance();
validDate.set(年,月,日);

日历的currentdate = Calendar.getInstance();

如果(currentDate.after(validDate)){
    catalog_outdated = 1;
}
 

解决方案

您code可能会降低到

 的SimpleDateFormat自卫队=新的SimpleDateFormat(DD / MM / YYYY);
日期strDate = sdf.parse(valid_until);
如果(新的日期()。之后(strDate)){
    catalog_outdated = 1;
}
 
ViewModel实例什么时候被回收

 的SimpleDateFormat自卫队=新的SimpleDateFormat(DD / MM / YYYY);
日期strDate = sdf.parse(valid_until);
如果(System.currentTimeMillis的()> strDate.getTime()){
    catalog_outdated = 1;
}
 

I am trying to compare a date in a String format to the current date. This is how I did it (haven't tested, but should work), but am using deprecated methods. Any good suggestion for an alternative? Thanks.

P.S. I really hate doing Date stuff in Java. There are so many ways to do the same thing, that you really aren't sure which one is the correct one, hence my question here.

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;
}

解决方案

Your code could be reduced to

SimpleDateFormat sdf = new SimpleDateFormat("dd/MM/yyyy");
Date strDate = sdf.parse(valid_until);
if (new Date().after(strDate)) {
    catalog_outdated = 1;
}

or

SimpleDateFormat sdf = new SimpleDateFormat("dd/MM/yyyy");
Date strDate = sdf.parse(valid_until);
if (System.currentTimeMillis() > strDate.getTime()) {
    catalog_outdated = 1;
}