-1

I want to compare two dates to categories Browser History... I have seen too many posts but didn't get any helpful,

My code is as :

 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();
        }
    }

} 

I want to do if the History date is earlier than ten days ago then notify the user. Any kind of help will be appreciated ,thank you.

sam
  • 113
  • 1
  • 9
  • Glad to see you joining Stack Overflow. When posting here, make your Question laser-focused on one narrow issue. Rather than paste all your real code, strip it down to the absolute minimum to demonstrate your issue. Make a [MCVE – Minimal, Complete, and Verifiable example](https://stackoverflow.com/help/mcve). – Basil Bourque Sep 29 '16 at 22:18

5 Answers5

1

tl;dr

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

java.time

You are using troublesome old date-time classes now supplanted by the java.time classes.

Time zone

Your code ignores the crucial issue of time zone in determining a date such as “today”.

Example code

The LocalDate class represents a date-only value without time-of-day and without time zone.

A time zone is crucial in determining a date. For any given moment, the date varies around the globe by zone. For example, a few minutes after midnight in Paris France is a new day while still “yesterday” in Montréal Québec.

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

Your input strings are in standard ISO 8601 format. The java.time classes use ISO 8601 formats by default when parsing/generating strings. So no need to specify a formatting pattern.

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

You say the boundary is ten days ago. Use the plus or minus methods to determine future/past dates.

LocalDate tenDaysAgo = today.minusDays( 10 );

Compare using compareTo, equals, isBefore, and isAfter methods.

Boolean alertUser = target.isBefore( tenDaysAgo );

About java.time

The java.time framework is built into Java 8 and later. These classes supplant the troublesome old date-time classes such as java.util.Date, .Calendar, & java.text.SimpleDateFormat.

The Joda-Time project, now in maintenance mode, advises migration to java.time.

To learn more, see the Oracle Tutorial. And search Stack Overflow for many examples and explanations.

Much of the java.time functionality is back-ported to Java 6 & 7 in ThreeTen-Backport and further adapted to Android in ThreeTenABP (see How to use…).

The ThreeTen-Extra project extends java.time with additional classes. This project is a proving ground for possible future additions to java.time. You may find some useful classes here such as Interval, YearWeek, YearQuarter, and more.

Community
  • 1
  • 1
Basil Bourque
  • 303,325
  • 100
  • 852
  • 1,154
0

Calendar is comparable so you can just use compare to. I would make curDate a calendar. Then (curDate.compareTo(calculatedDate) < 0) will be true if curDate is earlier than calculatedDate which you've set to ten days before today.

Ben
  • 1,285
  • 1
  • 9
  • 15
  • Calendar cal1 = Calendar.getInstance(); Calendar cal2= Calendar.getInstance(); try { cal1.setTime(simpleDate.parse(curDate)); } catch (ParseException e) { e.printStackTrace(); } try { cal2.setTime(simpleDate.parse(calculateDate())); } catch (ParseException e) { e.printStackTrace(); } if(cal1.compareTo(cal2)<0) {Toast.makeText(m_oContext,"Notify",Toast.LENGTH_SHORT).show(); } – sam Sep 29 '16 at 13:36
  • What do you mean by nothing is happening? If your date is equal or after calculated date the if statement will be false. – Ben Sep 29 '16 at 13:43
  • the dates are before the calculated date – sam Sep 29 '16 at 13:44
  • Also just as a tip since you already have the calendar objects I would use them instead of having your methods return strings. Then you can avoid the extra parse step to get the calendar objects. – Ben Sep 29 '16 at 13:44
  • Ok can you print the two dates you are comparing to the log. That way we can see what's happening. – Ben Sep 29 '16 at 13:46
  • you were right .... Unfortunately I was comparing and checking the history since same date that's why it was not returning true – sam Sep 30 '16 at 06:24
0

You can use before() Or after() to compare your calculated date with today's date

Developer
  • 324
  • 3
  • 13
  • Calendar cal1 = Calendar.getInstance(); Calendar cal2= Calendar.getInstance(); try { 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(); } – sam Sep 29 '16 at 13:38
  • Please refer this post if get any help please update http://stackoverflow.com/questions/6537535/check-date-with-todays-date – Developer Sep 29 '16 at 13:47
0
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;
}

Just call :

isHDateEarlier(curDate);
mariuss
  • 1,177
  • 2
  • 14
  • 30
-1

I had a problem with comparing dates a week ago, and searched for answers and this helped me: Find nearest date from a list. - The last answer talks about NavigableSet<>

Try using NavigableSet<Date> such as TreeSet<> and put your dates in the list. Than compare with lower or higher

Community
  • 1
  • 1
Zozinski
  • 73
  • 8
  • This is very superfluous for comparing dates. This would be more useful if you are trying to do a search for the closest date to a given date. – Ben Sep 29 '16 at 13:48