gpt4 book ai didi

java - 在 Android 中比较日期的最佳方法

转载 作者:IT老高 更新时间:2023-10-28 11:38:50 25 4
gpt4 key购买 nike

我正在尝试将字符串格式的日期与当前日期进行比较。这就是我的做法(尚未测试,但应该可以),但我使用的是不推荐使用的方法。对替代品有什么好的建议吗?谢谢。

附:我真的很讨厌用 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;
}

最佳答案

您的代码可以简化为

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

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

关于java - 在 Android 中比较日期的最佳方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10774871/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com