比较日期在Android的最佳途径 [英] Best way to compare dates in Android

查看:95
本文介绍了比较日期在Android的最佳途径的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想在一个字符串格式的日期来比较当前日期。这是我做的(没有测试,但应该工作),但我用德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;
}
 

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

这篇关于比较日期在Android的最佳途径的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆