【问题标题】:Unable to compare two dates in android无法比较android中的两个日期
【发布时间】:2016-09-29 13:19:02
【问题描述】:

我想将两个日期与类别浏览器历史记录进行比较... 我看了太多帖子,但没有得到任何帮助,

我的代码如下:

 private static String calculateDate()
{
    SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd");
    Calendar calendar = Calendar.getInstance();
    calendar.add(Calendar.DAY_OF_YEAR, -10);
    return simpleDateFormat.format(new Date(calendar.getTimeInMillis()));
}
private static String today()
{
    SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd");
    Calendar calendar = Calendar.getInstance();
    calendar.add(Calendar.DAY_OF_YEAR,0);
    return simpleDateFormat.format(new Date(calendar.getTimeInMillis()));
}

public void getBHistory()
{
    long startdates = 0;
    long enddates = 0;
    Date endDate = null;
    Date startDate=null;

    try
    {
        startDate = (Date)new SimpleDateFormat("yyyy-MM-dd")
                .parse(calculateDate());
        endDate = (Date)new SimpleDateFormat("yyyy-MM-dd")
                .parse(today());
        startdates = startDate.getTime();
        enddates = endDate.getTime();
    } catch (ParseException e)
    {
        e.printStackTrace();
    }

    // 0 = history, 1 = bookmark
    String sel = Browser.BookmarkColumns.BOOKMARK + " = 0" + " AND "
            + Browser.BookmarkColumns.DATE + " BETWEEN ? AND ?";
    Cursor mCur = m_oContext.getContentResolver().query(Browser.BOOKMARKS_URI, Browser.HISTORY_PROJECTION, sel,
            new String[]{
                    "" + startdates, "" + enddates
            }, null);
    mCur.moveToFirst();
    String title = "";
    String date_time = "";
    if (mCur.moveToFirst() && mCur.getCount() > 0)
    {
        while (!mCur.isAfterLast())
        {

            title = mCur.getString(mCur
                    .getColumnIndex(Browser.BookmarkColumns.TITLE));
            date_time = mCur.getString(mCur
                    .getColumnIndex(Browser.BookmarkColumns.DATE));
            SimpleDateFormat simpleDate= new SimpleDateFormat("yyyy-MM-dd");
            String curDate=simpleDate.format(new Date(Long.parseLong(date_time)));

            Toast.makeText(m_oContext,"History Time : "+curDate,Toast.LENGTH_SHORT).show();
            Toast.makeText(m_oContext,"Limit Time : "+calculateDate(),Toast.LENGTH_SHORT).show();
            //TODO: Compare these two dates here

            mCur.moveToNext();
        }
    }

} 

如果历史记录日期早于十天前,我想这样做,然后通知用户。 任何形式的帮助将不胜感激,谢谢。

【问题讨论】:

  • 很高兴看到您加入 Stack Overflow。在这里发帖时,让你的问题集中在一个狭窄的问题上。与其粘贴所有真实代码,不如将其剥离到绝对最低限度以证明您的问题。创建MCVE – Minimal, Complete, and Verifiable example

标签: java android date calendar


【解决方案1】:

tl;博士

Boolean alertUser = 
    LocalDate.parse( "2016-01-02" )
             .isBefore( 
                 LocalDate.now( ZoneId.of( “America/Montreal” ) )
                          .minusDays( 10 ) 
             ) ;

java.time

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

时区

您的代码在确定诸如“今天”之类的日期时忽略了时区这一关键问题。

示例代码

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

时区对于确定日期至关重要。对于任何给定的时刻,日期在全球范围内因区域而异。例如,Paris France 中午夜过后几分钟是新的一天,而 Montréal Québec 中仍然是“昨天”。

ZoneId z = ZoneId.of( “America/Montreal” );
LocalDate today = LocalDate.now( z );

您的输入字符串采用标准ISO 8601 格式。 java.time 类在解析/生成字符串时默认使用ISO 8601 格式。所以不需要指定格式模式。

LocalDate target = LocalDate.parse( "2016-01-02" );

你说边界是十天前。使用plusminus 方法来确定未来/过去的日期。

LocalDate tenDaysAgo = today.minusDays( 10 );

使用compareToequalsisBeforeisAfter 方法进行比较。

Boolean alertUser = target.isBefore( tenDaysAgo );

关于java.time

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

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

要了解更多信息,请参阅Oracle Tutorial。并在 Stack Overflow 上搜索许多示例和解释。

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

ThreeTen-Extra 项目通过附加类扩展了 java.time。该项目是未来可能添加到 java.time 的试验场。您可以在这里找到一些有用的类,例如IntervalYearWeekYearQuartermore

【讨论】:

    【解决方案2】:

    日历具有可比性,因此您可以使用 compare to。我会让 curDate 成为日历。如果 curDate 早于您设置为今天前十天的计算日期,则 (curDate.compareTo(calculatedDate) < 0) 将为真。

    【讨论】:

    • 日历 cal1 = Calendar.getInstance();日历 cal2= Calendar.getInstance();尝试 { cal1.setTime(simpleDate.parse(curDate)); } catch (ParseException e) { e.printStackTrace(); } 尝试 { cal2.setTime(simpleDate.parse(calculateDate())); } catch (ParseException e) { e.printStackTrace(); } if(cal1.compareTo(cal2)
    • 什么都没有发生是什么意思?如果您的日期等于或在计算日期之后,则 if 语句将是错误的。
    • 日期早于计算日期
    • 也只是作为一个提示,因为您已经有了日历对象,我会使用它们而不是让您的方法返回字符串。然后您可以避免额外的解析步骤来获取日历对象。
    • 好的,您可以打印您要与日志进行比较的两个日期吗?这样我们就可以看到正在发生的事情。
    【解决方案3】:

    你可以使用 前() 或者 后() 将您计算的日期与今天的日期进行比较

    【讨论】:

    • 日历 cal1 = Calendar.getInstance();日历 cal2= Calendar.getInstance();尝试 { cal1.setTime(simpleDate.parse(curDate)); cal2.setTime(simpleDate.parse(calculateDate())); } catch (ParseException e) { e.printStackTrace(); } if(cal1.before(cal2)) { Toast.makeText(m_oContext,"Notify", Toast.LENGTH_SHORT).show(); }
    • 如果有任何帮助请参考这篇文章请更新stackoverflow.com/questions/6537535/check-date-with-todays-date
    【解决方案4】:
    public boolean isHDateEarlier(String historyDate){
    
          String[] historySplitStrings= historyDate.split("-");
          String[] tenDaysEarlierStrings = calculateDate().split("-");
    
          int historyYear = Integer.parseInt(historySplitStrings[0]);
          int daysYear = Integer.parseInt(tenDaysEarlierStrings [0]);
          int historyMonth = Integer.parseInt(historySplitStrings[1]);
          int daysMonth = Integer.parseInt(tenDaysEarlierStrings [1]);
          int historyDay = Integer.parseInt(historySplitStrings[2]);
          int daysDay = Integer.parseInt(tenDaysEarlierStrings [2]);
    
    
    if(historyYear  < daysYear ){//check year
          return true;
    }
    
        if(historyMonth  < daysMonth  &&    
              historyYear   <= daysYear ){//check month
              return true;
        }
    
    
    
      if(historyDay < daysDay && 
            historyYear <= daysYear && 
            historyMonth <= daysMonth){//check day
              return true;
      }
    
    return false;
    }
    

    只要打电话:

    isHDateEarlier(curDate);
    

    【讨论】:

    • 我们如何将
    • @sam 对不起我的错误,忘记将它们解析为 int。
    • 在这种情况下,日期在 curDate 之前
    • 此函数验证您作为参数提供的日期是否早于 10 天前。它工作正常,例如“2016-09-17”应该返回 true。
    【解决方案5】:

    我在比较一周前的日期时遇到问题,我搜索了答案,这对我有帮助:Find nearest date from a list。 - 最后一个答案是关于NavigableSet&lt;&gt;

    尝试使用NavigableSet&lt;Date&gt;,例如TreeSet&lt;&gt;,并将您的日期放入列表中。 比与lowerhigher 比较

    【讨论】:

    • 这对于比较日期来说是非常多余的。如果您尝试搜索与给定日期最接近的日期,这将更加有用。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-02-12
    • 2016-06-25
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多