【发布时间】:2022-02-01 08:04:24
【问题描述】:
我试图用 ("MM/dd/yyyy") 抓取一个字符串(日期)解析,然后用 (“EEE MMM dd kk:mm:ss z yyyy”)然后再次解析该字符串,创建格式为(“EEE MMM dd kk:mm:ss z yyyy”)的日期。所以我可以比较两个日期的格式(“EEE MMM dd kk:mm:ss z yyyy”)
没有得到任何解析错误,但我试图用它来比较两个日期。遇到无法创建列表的问题,因为我的比较不起作用。在这种类型的转换方面需要一点帮助
private Date getDateNDaysAgo(int numDays) {
log.debug("getDateNDaysAgo 1 " + numDays);
Calendar cal = Calendar.getInstance();
Date returnDate = null;
cal.add(Calendar.DATE, -(numDays));
returnDate = cal.getTime();
log.debug("getDateNDaysAgo 2" + returnDate);
return (returnDate);
}
String EffectiveHireString = null;
String EffectiveHireDate = null;
Date returnEffectiveHireDate = null;
Date thresholdDate = null;
Date newEffectiveHireDate=null;
boolean isAccountCreatedOver25Days = false;
link = (Link)itrLinkResults.next();
// only pull active accounts
if(!link.isDisabled()) {
if(link.getAttribute("lastLogon") != null){
log.debug("QueryParameter: lastLogon (1): not null");
lastLogon = link.getAttribute("lastLogon");
}
if(link.getAttribute("EffectiveHireDate") != null){
log.debug("QueryParameter: EffectiveHireDate (1): not null");
acuEffectiveHireDate = link.getAttribute("EffectiveHireDate");
if(Util.isNotNullOrEmpty(EffectiveHireDate)) {
DateFormat df = new SimpleDateFormat("EEE MMM dd kk:mm:ss z yyyy");
SimpleDateFormat sdf = new SimpleDateFormat("MM/dd/yyyy");
SimpleDateFormat formatter = new SimpleDateFormat("EEE MMM dd kk:mm:ss z yyyy");
try {
newEffectiveHireDate = sdf.parse(EffectiveHireDate);
EffectiveHireString = df.format(newEffectiveHireDate);
returnEffectiveHireDate = formatter.parse(EffectiveHireString);
thresholdDate = getDateNDaysAgo(25);
log.debug("thresholdDate" + thresholdDate);
if(returnEffectiveHireDate.compareTo(thresholdDate) < 0){
log.debug("returnEffectiveHireDate 2" + returnEffectiveHireDate);
isAccountCreatedOver25Days = true;**
}
}
catch (ParseException e) {
log.error("Error attempting to parse EffectiveHireDate Date");
}
}
}
【问题讨论】:
-
但我试图用它来比较两个日期。如果你能解释比较标准会很有帮助。另外,您说比较日期,但您的格式包含时间元素。
-
您的问题令人费解且令人困惑。为清楚起见重写。提示: (a) 切勿使用
Date/Calendar/DateFormat。几年前,它们被 java.time 类所取代。 (b) 不要为解析生成本地化字符串。仅使用标准 ISO 8601 格式进行数据交换。 java.time 类默认使用标准格式来生成/解析字符串。 (c) 在此处发布代码时,将其精简到显示您的问题所需的最低限度。 -
我正在比较日期/时间以查看用户是否在 25 天内登录系统。这些是我必须使用的类。
-
我遇到了字符串到日期解析的问题 - 格式化为字符串然后解析回日期。
-
你说“这些是我必须使用的类。”为什么?您使用的是非常旧的 Java 版本吗?你在安卓上吗? (有适用于 Android 的 java.time API 版本。)