-2

I've got an object with a field timestamp with type java.sql.Timestamp;. And I need to get objects with yesterday date from a collection. How to get them? I mean I need something like this

for(int i = 0; i < items.size(); i++) {
   (if the items.get(i).date == yesterday_date)
       (get object)
}
Subhrajyoti Majumder
  • 40,646
  • 13
  • 77
  • 103
lapots
  • 12,553
  • 32
  • 121
  • 242

3 Answers3

2

You can get yesterday's Date by following approach Answered by Jiger Joshi.

And by using new Timestamp(java.util.Date) you can get yesterday's timestamp, you should use Timestamp#equals to equaling two different timestamp.

if (items.get(i).date.equals(getYesterdaytimestamp())){
   ...
}

And there are something which you must consider while implementing this. Calender#getTime which returns Date object and date object contains date with time, so in that case your equaling date or timestamp must be exactly equals with yesterday's date and time.

If requirement is, it needs to equal just yesterday no not where time is not considerable fact. In that case you need to equals two timestamp after discarding time part.

if (equalsWithYesterday(items.get(i).date)){
    ...
}
...
public boolean equalsWithYesterday(Timestamp st){
    DateFormat dateFormat = new SimpleDateFormat("yyyy/MM/dd"); // Time part has discarded
    Calendar cal = Calendar.getInstance();
    cal.add(Calendar.DATE, -1);
    Date yesterday = dateFormat.parse(dateFormat.format(cal.getTime())); // get yesterday's Date without time part
    Date srcDate = new Date(st);
    Date srcDateWithoutTime =dateFormat.parse(dateFormat.format(srcDate));
    return yesterday.equals(srcDateWithoutTime ); // checks src date equals yesterday.
}
Community
  • 1
  • 1
Subhrajyoti Majumder
  • 40,646
  • 13
  • 77
  • 103
2

You can convert the timestamp object to date object like this:

Date date = new Date(items.get(i).getTime());

or you can simply use method Timestamp#compareTo(Date o)

items.get(i).compareTo(yesterday_date);
Baby
  • 5,062
  • 3
  • 30
  • 52
1

I hope you are not interested to compare the time?

Simply use Calendar class to extract the day, month, year etc. from the date and simply compare it.

Use Calendar#get() method to get the specific field from the date object.


How to subtract one day from the current date?

// get Calendar with current date
Calendar cal = Calendar.getInstance();

// get yesterday's date
cal.add(Calendar.DATE, -1);

// get components of yesterday's date
int month = cal.get(Calendar.MONTH) + 1; // 0 for January, 1 for Feb and so on
int day = cal.get(Calendar.DATE);
int year = cal.get(Calendar.YEAR);

// get yesterday's date in milliseconds
long lMillis = cal.getTime().getTime();
Braj
  • 46,415
  • 5
  • 60
  • 76