我有一个验证方法,它将两个输入作为开始日期和结束日期,并检查结束日期是否有效,即开始日期之后。
我使用Calendar方法getTimeInMillis()
来获取两个日期的毫秒数并获得差异。如果差异为负,则其无效结束日期即结束日期在开始日期之前。
结束日期的毫秒值应始终大于开始日期。但在某些情况下getTimeInMillis()
在开始日期时会给予更大的价值。
这是我的代码:
public class ValidationProcessor {
private void testTimeDiff(String startDate, String endDate) throws Exception {
Calendar cal1 = Calendar.getInstance(TimeZone.getTimeZone("UTC"));
Calendar cal2 = Calendar.getInstance(TimeZone.getTimeZone("UTC"));
// Set the dates for calendars
cal1.set(Integer.parseInt(startDate.split("-")[0]), Integer.parseInt(startDate.split("-")[1]),
Integer.parseInt(startDate.split("-")[2]));
cal2.set(Integer.parseInt(endDate.split("-")[0]), Integer.parseInt(endDate.split("-")[1]),
Integer.parseInt(endDate.split("-")[2]));
long milis1 = cal1.getTimeInMillis();
long milis2 = cal2.getTimeInMillis();
System.out.println("milis1::: " + milis1);
System.out.println("milis2::: " + milis2);
long diff = milis2 - milis1;
System.out.println("diff::: " + diff);
if (diff <= 0) {
throw new Exception("Invalid End Date. End Date Must Be After Start Date");
}
}
public static void main(String args[]) {
ValidationProcessor test = new ValidationProcessor();
try {
test.testTimeDiff("2015-01-31", "2015-02-01");
} catch (Exception ex) {
ex.printStackTrace();
}
}
}
输出结果为:
milis1::: 1425367717308
milis2::: 1425194917308
diff::: -172800000
java.lang.Exception: Invalid End Date. End Date Must Be After Start Date
此处 2015-01-31 是开始日期, 2015-02-01 是结束日期。 由于开始日期(2015-01-31)以毫秒为单位以比结束日期(2015-02-01)更大的值,因此它给出了错误的结果。
这是getTimeInMillis()
类的方法Calendar
的问题,还是我做错了什么?
答案 0 :(得分:1)
这可能是因为Calendar.getInstance()
为您提供了当前时间戳(所有字段,如小时,分钟等),以及你没有明确地清楚那些额外的字段(你只设置年,月和日期)。
另外,请记住,数据Calendar.set(int year, int month, int day)
使用 0为基础的月份(例如Jan = 0,2月= 1等),因此您的转化目前是错误的。
更新:我认为这是两者的结合;您的考试日期2015-01-31被解析为2015年2月31日,当然无效,导致意外的getTimeInMillis()
值。
答案 1 :(得分:0)
使用cal1.getTime().getAfter(cal2.getTime());
更新1
要填写您的日历,您应该按照以下方式填写
//cal1.set(Integer.parseInt(startDate.split("-")[0]), Integer.parseInt(startDate.split("-")[1]), Integer.parseInt(startDate.split("-")[2]));
//cal2.set(Integer.parseInt(endDate.split("-")[0]), Integer.parseInt(endDate.split("-")[1]), Integer.parseInt(endDate.split("-")[2]));
DateFormat df = new SimpleDateFormat("yyyy-MM-dd");
cal1.setTime(df.parse(startDate));
cal2.setTime(df.parse(endDate));
然后您的原始代码也会起作用。
更新2
虽然您可以避免将Calendar用于此特定用途并直接使用日期对象。
Date date1 = df.parse(startDate);
Date date2 = df.parse(endDate);
long milis1 = date1.getTime();
long milis2 = date2.getTime();
答案 2 :(得分:0)
一个问题是,如果我们将月份设置为-1,那么它会给出正确的结果。 等,
cal1.set(Integer.parseInt(startDate.split("-")[0]), Integer.parseInt(startDate.split("-")[1]) -1,
Integer.parseInt(startDate.split("-")[2]));
cal2.set(Integer.parseInt(endDate.split("-")[0]), Integer.parseInt(endDate.split("-")[1]-1),
Integer.parseInt(endDate.split("-")[2]));
它给出,差异为86400000