Subtrair Data?

9 respostas
sanson

Olá pessoal!
Estou precisando fazer uma subtração de datas que me retorne quantos dias entre uma data e outra!
Ex:
(10/01/2003) - (01/01/2003) e do resultado = 9 dias

Obigado pela atenção

Luiz Bernardo

9 Respostas

elvishr

Vc quer o código pronto???

Passa a dúvida que tem a respeito do seu código pra gente poder ajudar no que for preciso

:slight_smile:

Daniel_Quirino_Olive

“sanson”:
Olá pessoal!
Estou precisando fazer uma subtração de datas que me retorne quantos dias entre uma data e outra!
Ex:
(10/01/2003) - (01/01/2003) e do resultado = 9 dias

Obigado pela atenção

Luiz Bernardo</blockquote>

http://java.sun.com/j2se/1.4.2/docs/api/java/util/GregorianCalendar.html
Veja o método roll.

sanson

Não entendi!!
Se alguem tiver um exemplo poste aqui no forum!

Obrigado

Luiz Bernardo

[/quote]

dreamspeaker

“Daniel Quirino Oliveira”:

http://java.sun.com/j2se/1.4.2/docs/api/java/util/GregorianCalendar.html
Veja o método roll.

Eu também não entendi. O que esse método vai ajudar nesse caso?

Daniel_Quirino_Olive

Ahh opa. É o que dá não ler um post até o final. :oops:

luiz_ross

Ué, a explicação do método ja diz tudo

Daniel_Quirino_Olive

Retirado daqui:

/**
 * Diff.java 
 * A sound simple question. 
 * What is the date difference between these two date/time 
 * 12-31-2002 23:59:59 and 01-01-2003 00:00:01? 
 * The real time difference is only 2 seconds. 
 * However, the date/month/year differences are all ones.
 * The week difference is zero.
 * The answer will also be different when you are in a different time zone. 
 * The different dates in London, UK does not mean different dates in Beijing, China.
 * How do we get there?
 */
 
import java.text.SimpleDateFormat;
import java.text.ParseException;
import java.util.Date;
import java.util.Calendar;
import java.util.TimeZone;

public class Diff
{
    public static void printDiff(String sdate1, String sdate2, String fmt, TimeZone tz)
    {
        SimpleDateFormat df = new SimpleDateFormat(fmt);

        Date date1  = null;
        Date date2  = null;
        
        try 
        {
            date1 = df.parse(sdate1); 
            date2 = df.parse(sdate2); 
        }
        catch (ParseException pe)
        {
            pe.printStackTrace();
        }

        Calendar cal1 = null; 
        Calendar cal2 = null;
        
        if (tz == null)
        {
          cal1=Calendar.getInstance(); 
          cal2=Calendar.getInstance(); 
        }
        else
        {
          cal1=Calendar.getInstance(tz); 
          cal2=Calendar.getInstance(tz); 
        }
          
        
        // different date might have different offset
        cal1.setTime(date1);          
        long ldate1 = date1.getTime() + cal1.get(Calendar.ZONE_OFFSET) + cal1.get(Calendar.DST_OFFSET);
        
        cal2.setTime(date2);
        long ldate2 = date2.getTime() + cal2.get(Calendar.ZONE_OFFSET) + cal2.get(Calendar.DST_OFFSET);
        
        // Use integer calculation, truncate the decimals
        int hr1   = (int)(ldate1/3600000); //60*60*1000
        int hr2   = (int)(ldate2/3600000);

        int days1 = (int)hr1/24;
        int days2 = (int)hr2/24;

        
        int dateDiff  = days2 - days1;
        int weekOffset = (cal2.get(Calendar.DAY_OF_WEEK) - cal1.get(Calendar.DAY_OF_WEEK))<0 ? 1 : 0;
        int weekDiff  = dateDiff/7 + weekOffset; 
        int yearDiff  = cal2.get(Calendar.YEAR) - cal1.get(Calendar.YEAR); 
        int monthDiff = yearDiff * 12 + cal2.get(Calendar.MONTH) - cal1.get(Calendar.MONTH);

        
        System.out.println();  
        System.out.println("DateTime 1: " + sdate1);
        System.out.println("DateTime 2: " + sdate2);
        
        System.out.println("Date difference : " + dateDiff);
        System.out.println("Week difference : " + weekDiff);
        System.out.println("Month difference: " + monthDiff);
        System.out.println("Year difference : " + yearDiff);        
    }
    
    
    public static void main(String[] args)
    {
        String fmt    = null;
        String sdate1 = null;
        String sdate2 = null;
        
        fmt    = "MM-dd-yyyy HH:mm:ss";
        sdate1 = "12-31-2002 23:59:59";
        sdate2 = "01-01-2003 00:00:01";
        
        // Result is independent of format
        // null will print in local timezone
        // Print out 1 day, i month, 1 year difference
        System.out.println("In your local time:");  
        printDiff(sdate1, sdate2, fmt, null);
        
        // Beijing timezone, if you are not in +8 timezone, the resuls are all 0's
        System.out.println("In Beijing time:");  
        printDiff(sdate1, sdate2, fmt, TimeZone.getTimeZone("GMT+08:00"));
        
        // for testing the weekDiff
        fmt    = "MM-dd-yyyy HH:mm:ss";
        sdate1 = "12-31-2002 23:59:59";
        sdate2 = "01-06-2003 00:00:01";
        System.out.println("In your local time:");  
        printDiff(sdate1, sdate2, fmt, null);
        
        fmt    = "MM-dd-yyyy HH:mm:ss";
        sdate1 = "01-04-2003 23:59:59";
        sdate2 = "01-05-2003 00:00:01";
        System.out.println("In your local time:");  
        printDiff(sdate1, sdate2, fmt, null);
        
        // something interesting here
        fmt    = "MM-dd-yyyy HH:mm:ss";
        sdate1 = "12-31-1996 23:59:59";
        sdate2 = "01-01-1997 00:00:01";
        System.out.println("In your local time:");  
        printDiff(sdate1, sdate2, fmt, null);
    }
}
dreamspeaker

Mas só isso não resolve o problema dele, luis. Pelo menos eu não tô conseguindo enxergar!

wbsouza

Dê uma olhada em uma classe que faz isso. Com poucas alterações vc coloca ela calculando a diferença em dias usando dois objetos do tipo Date ou GregorianCalendar.

http://www.javatutorials.org/javatutorials/src/datediff/DateDiff.zip

[]s, Welington B. Souza

Criado 24 de outubro de 2003
Ultima resposta 24 de out. de 2003
Respostas 9
Participantes 6