比较两个日历对象 [英] Comparing two Calendar objects

查看:120
本文介绍了比较两个日历对象的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想比较两个日历对象,看看它们是否包含相同的日期。



我实现了这个,我不能想到任何失败的情况:

  private static boolean areEqualDays(Calendar c1,Calendar c2){
SimpleDateFormat sdf = new SimpleDateFormat(dd-MM-yyyy);
return(sdf.format(c1.getTime())。equals(sdf.format(c2.getTime())));这个方法是正确的,还是应该按字段比较c1和c2字段? / p>

解决方案


我实现了这个,我不能想到它应该失败的任何情况


如果两个日历在不同的时区,它们会失败 - 它们可以表示完全相同的毫秒但根据时区,该时间可能会落入不同的日期。



如果两个日历代表不同的日历系统,也可能会失败 - 即使它们代表相同的天,如果两个日历表示不同的日期,您可以认为它应该失败。



个人,我会强烈使用具有 LocalDate 类型的 Joda时间来表示日期 - 这将摆脱时区问题,但不是日历系统问题。



(此外,执行字符串操作只是为了比较的目的是丑陋的 - 我可以使用相同的日历系统,只需直接检查 calendar.get(Calendar.YEAR)等)。


I want to compare two Calendar objects to see if they both contain the same date. I don't care about any value below days.

I've implemented this and I can't think about any case where it should fail:

private static boolean areEqualDays(Calendar c1, Calendar c2) {
    SimpleDateFormat sdf = new SimpleDateFormat("dd-MM-yyyy");
    return (sdf.format(c1.getTime()).equals(sdf.format(c2.getTime())));
}

Is this approach correct or should I compare c1 and c2 field by field?

解决方案

I've implemented this and I can't think about any case where it should fail

It will fail if the two calendars are in different time zones - they could represent the exact same millisecond, but that instant could fall into different days based on the time zone.

It will also arguably fail if the two calendars represent different calendar systems - even if they represent the same "day", if the two calendars would represent that day differently, you could argue that it should fail.

Personally, I would strongly advise you to use Joda Time which has a LocalDate type to represent just a date - that would get rid of the time zone issue, but not the calendar system issue. If you can always assume that you're using the same calendar system, then that's okay.

(Additionally, performing string operations just for comparison purposes is ugly - I'd just check calendar.get(Calendar.YEAR) etc directly.)

这篇关于比较两个日历对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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