使用GregorianCalendar比较日期

时间:2016-09-13 21:47:53

标签: android date gregorian-calendar

我试图将当前日期(2016-08-31)与给定日期(2016-08-31)进行比较。 我目前的移动设备时区是太平洋时间GMT-08:00。

如果我禁用自动日期&设备上的时区和设置时区为GMT + 08:00珀斯,method1将返回true但method2返回false;

方法2的结果是预期的,因为我比较没有时区的日期,所以" 2016-08-31"之前" 2016-08-31"是假的;为什么method1返回true?

    public boolean method1() {
        try {
            GregorianCalendar currentCalendar = new GregorianCalendar();
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
            Date endDate = sdf.parse("2016-08-31");
            Calendar endCalendar = new GregorianCalendar();
            endCalendar.setTime(endDate);

            if (endCalendar.before(currentCalendar)) {
                return true;
            } else {
                return false;
            }
        } catch (ParseException e) {
            ...
        }
    }


    public boolean method2() {    
        try {
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
            Date currentDate = sdf.parse(formatter.format(new Date())); 
            Date endDate = sdf.parse("2016-08-31");

            if (endDate.before(currentDate)) {
                return true;
            } else {
                return false;
            }

        } catch (ParseException e) {
            ...
        }
    }

1 个答案:

答案 0 :(得分:1)

有无时区

可能的解释:您的代码混合使用分区和UTC日期时间对象。在某些行中,您有一个对象分配了一个时区(java.util.Calendar),即JVM的当前默认时区。在其他行中,您在UTC中修复了一个对象(java.util.Date)。 Australia/Perth时区比UTC早8小时,所以你当然可以看到日期的差异。打印出他们的毫秒数 - 从纪元数字开始就可以明显地得出比较结果。

给自己一个青睐:避免这些臭名昭着的老课程。改为使用java.time。

Boolean isFuture = 
    LocalDate.parse( "2016-08-31" )
             .isAfter( LocalDate.now( ZoneId.of( "Australia/Perth" ) ) ) ;

使用java.time

您正在使用麻烦的旧旧日期时间类,现在已被java.time类取代。

获取当前日期需要时区。对于任何给定的时刻,日期在全球范围内因地区而异。如果省略,则隐式应用JVM的当前默认时区。最好指定,因为默认值可以随时改变。

指定proper time zone name。切勿使用诸如ESTIST之类的3-4字母缩写,因为它们不是真正的时区,不是标准化的,甚至不是唯一的(!)。

ZoneId z = ZoneId.of( "Australia/Perth" ) ;

LocalDate类表示没有时间且没有时区的仅限日期的值。

LocalDate today = LocalDate.now( z );

您的输入字符串恰好符合标准ISO 8601格式。所以直接用LocalDate解析。无需指定格式化模式。

LocalDate ld = LocalDate.parse( "2016-08-31" );

isBeforeisAfterisEqualcompareTo进行比较。

Boolean isFuture = ld.isAfter( today );

关于java.time

java.time框架内置于Java 8及更高版本中。这些类取代了麻烦的旧日期时间类,例如java.util.Date.Calendar和& java.text.SimpleDateFormat

现在位于Joda-Timemaintenance mode项目建议迁移到java.time。

要了解详情,请参阅Oracle Tutorial。并搜索Stack Overflow以获取许多示例和解释。

大部分java.time功能都被反向移植到Java 6& ThreeTen-Backport中的7,并进一步适应Android中的ThreeTenABP(见How to use…)。

ThreeTen-Extra项目使用其他类扩展java.time。该项目是未来可能添加到java.time的试验场。您可以在此处找到一些有用的课程,例如IntervalYearWeekYearQuarter等。