Pergunta

I'm making an android app and I'm trying to get the day before yesterday each time that I click a button.

If I click the button it should bring me yesterday, if click it again it should bring me the day before yesterday, if I do it again, the day before that, and so on.

This is what I'm using to get yesterday:

Calendar cal = Calendar.getInstance();
cal.set(Calendar.HOUR_OF_DAY, 23);
cal.set(Calendar.MINUTE, 59);
cal.set(Calendar.SECOND, 59);
cal.add(Calendar.DATE, -1);
long yesterdayEnd = cal.getTimeInMillis() / 1000;
Foi útil?

Solução

Here's 2 ways to achieve what you want.

private Calendar yesterday = null;
...
public long getYesterday() {
  if (this.yesterday == null) {
    this.yesterday = Calendar.getInstance();
    this.yesterday.set(Calendar.HOUR_OF_DAY, 23);
    this.yesterday.set(Calendar.MINUTE, 59);
    this.yesterday.set(Calendar.SECOND, 59);
    this.yesterday.set(Calendar.MILLISECOND, 0);
  }

  this.yesterday.add(Calendar.DATE, -1);
  return this.yesterday.getTimeInMillis() / 1000;
}

or

private int backDays = 0;
...
public long getYesterday() {
  Calendar yesterday = Calendar.getInstance();
  yesterday.set(Calendar.HOUR_OF_DAY, 23);
  yesterday.set(Calendar.MINUTE, 59);
  yesterday.set(Calendar.SECOND, 59);
  yesterday.set(Calendar.MILLISECOND, 0);

  yesterday.add(Calendar.DATE, -backDays);
  return yesterday.getTimeInMillis() / 1000;
}

In the second one, you need to increase backDays each time your button is pushed while it isn't necessary in the first one. The method need to be called when your button is pushed.

If you want to reset the value to start from scratch, in the first one, use yesterday = null; and backDays = 0; in the second one.

Also, I would suggest you use a Calendar, or a Date, variable instead of a long one. Changing the methods to public Calendar getYesterday() {or even public Date getYesterday() { would be cleaner than using a long.

Outras dicas

Make it a field in your Activity:

private Calendar cal;

in onCreate:

cal = Calendar.getInstance();
cal.set(Calendar.HOUR_OF_DAY, 23);
cal.set(Calendar.MINUTE, 59);
cal.set(Calendar.SECOND, 59);

in the Button onClickListener as an inner class of Activity:

cal.add(Calendar.DATE, -1);
Licenciado em: CC-BY-SA com atribuição
Não afiliado a StackOverflow
scroll top