baTimá
baTimá

Reputation: 544

How to show the date difference in days?

I need to get the actual date and minus the date from the value in the database, the date now is now and the date in the database is this.vencimento.

  public boolean getDiasVencido() {
    boolean diasvencido = false;                

    SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd");
    Date datahora = null;       
    try {
        datahora = (Date) formatter.parse(this.vencimento);
    } catch (ParseException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
    Date now = new Date();      
    if(datahora.compareTo(now) < 0 ) { 


        long diff = "DATE NOW - DATE FROM DATABASE (this.vencimento)";
        long days = diff / (24 * 60 * 60 * 1000);

        diasvencido = true; 

    }
    return diasvencido;
}

the variables setted in the class:

     public class classetitulo {

private String documento;
private String vencimento;
private Double valor;
private Double multa;
private Double juros;

public classetitulo() {}

public classetitulo(String documento, String vencimento, Double valor, Double multa, Double juros) {
    this.documento = documento;
    this.vencimento = vencimento;
    this.valor = valor;
    this.juros = juros;
    this.multa = multa;
}

I don't know much how to do it. thanks in advance.

Upvotes: 1

Views: 420

Answers (2)

baTim&#225;
baTim&#225;

Reputation: 544

Try this:

this.diasvencido = Integer.parseInt(""+(((now.getTime() - datahora.getTime()) / (1000 * 60 * 60 * 24))));

It will get the date in time and it will times by the day giving the result to Days.

Upvotes: 1

kaneda
kaneda

Reputation: 6187

You could try this. This is how to calculate how many days have passed until now:

long now = System.currentTimeMillis();
SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd");
try {
     long dataHora = formatter.parse(this.vencimento).getTime();
     long duration = Math.abs(now - dataHora);
     long diff = duration / DateUtils.DAY_IN_MILLIS;
}
catch (ParseException e) {
     e.printStackTrace();
}

The class DateUtils is available since API Level 3, but you can always calculate the value of DateUtils.DAY_IN_MILLIS by yourself.

Upvotes: 0

Related Questions