Różnica w dniach między dwiema datami w Javie?

Muszę znaleźć ilość dni pomiędzy dwoma datami: jeden pochodzi z raportu, a drugi z aktualnej daty. Mój fragment:

  int age=calculateDifference(agingDate, today);

Tutaj calculateDifference jest metodą prywatną, agingDate i today są obiektami Date, tylko dla wyjaśnienia. Śledziłem dwa artykuły z forum Java, Wątek 1 / wątek 2 .

Działa dobrze w samodzielnym programie, chociaż kiedy włączam to do mojej logiki, aby przeczytać z raportu, dostaję niezwykłą różnicę w wartościach.

Dlaczego to się dzieje i jak Mogę to naprawić?

EDIT:

Dostaję większą liczbę dni w porównaniu z rzeczywistą ilością dni.
public static int calculateDifference(Date a, Date b)
{
    int tempDifference = 0;
    int difference = 0;
    Calendar earlier = Calendar.getInstance();
    Calendar later = Calendar.getInstance();

    if (a.compareTo(b) < 0)
    {
        earlier.setTime(a);
        later.setTime(b);
    }
    else
    {
        earlier.setTime(b);
        later.setTime(a);
    }

    while (earlier.get(Calendar.YEAR) != later.get(Calendar.YEAR))
    {
        tempDifference = 365 * (later.get(Calendar.YEAR) - earlier.get(Calendar.YEAR));
        difference += tempDifference;

        earlier.add(Calendar.DAY_OF_YEAR, tempDifference);
    }

    if (earlier.get(Calendar.DAY_OF_YEAR) != later.get(Calendar.DAY_OF_YEAR))
    {
        tempDifference = later.get(Calendar.DAY_OF_YEAR) - earlier.get(Calendar.DAY_OF_YEAR);
        difference += tempDifference;

        earlier.add(Calendar.DAY_OF_YEAR, tempDifference);
    }

    return difference;
}

Uwaga:

Niestety żadna z odpowiedzi nie pomogła mi rozwiązać problemu. Udało mi się rozwiązać ten problem z pomocą Biblioteki Joda-time.
Author: Community, 2010-07-21

20 answers

Sugerowałbym użycie doskonałej biblioteki Joda Time zamiast wadliwej Javy.util.Randka i przyjaciele. Możesz po prostu napisać

import java.util.Date;
import org.joda.time.DateTime;
import org.joda.time.Days;

Date past = new Date(110, 5, 20); // June 20th, 2010
Date today = new Date(110, 6, 24); // July 24th 
int days = Days.daysBetween(new DateTime(past), new DateTime(today)).getDays(); // => 34
 147
Author: Adam Schmideg,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2014-08-20 10:48:07

Mogę być za późno, aby dołączyć do gry, ale co mi tam? :)

Myślisz, że to jest problem z gwintem? Jak na przykład korzystasz z wyjścia tej metody? Lub

Czy możemy zmienić twój kod tak, aby zrobił coś tak prostego jak:

Calendar calendar1 = Calendar.getInstance();
    Calendar calendar2 = Calendar.getInstance();
    calendar1.set(<your earlier date>);
    calendar2.set(<your current date>);
    long milliseconds1 = calendar1.getTimeInMillis();
    long milliseconds2 = calendar2.getTimeInMillis();
    long diff = milliseconds2 - milliseconds1;
    long diffSeconds = diff / 1000;
    long diffMinutes = diff / (60 * 1000);
    long diffHours = diff / (60 * 60 * 1000);
    long diffDays = diff / (24 * 60 * 60 * 1000);
    System.out.println("\nThe Date Different Example");
    System.out.println("Time in milliseconds: " + diff
 + " milliseconds.");
    System.out.println("Time in seconds: " + diffSeconds
 + " seconds.");
    System.out.println("Time in minutes: " + diffMinutes 
+ " minutes.");
    System.out.println("Time in hours: " + diffHours 
+ " hours.");
    System.out.println("Time in days: " + diffDays 
+ " days.");
  }
 48
Author: Suji,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2010-07-29 16:47:26

Diff / (24 * etc) nie bierze pod uwagę strefy czasowej, więc jeśli domyślna Strefa czasowa ma w sobie DST, może odrzucić obliczenia.

Ten link ma ładną małą implementację.

Oto źródło powyższego linku w przypadku, gdy link pójdzie w dół:

/** Using Calendar - THE CORRECT WAY**/  
public static long daysBetween(Calendar startDate, Calendar endDate) {  
  //assert: startDate must be before endDate  
  Calendar date = (Calendar) startDate.clone();  
  long daysBetween = 0;  
  while (date.before(endDate)) {  
    date.add(Calendar.DAY_OF_MONTH, 1);  
    daysBetween++;  
  }  
  return daysBetween;  
}  

I

/** Using Calendar - THE CORRECT (& Faster) WAY**/  
public static long daysBetween(final Calendar startDate, final Calendar endDate)
{
  //assert: startDate must be before endDate  
  int MILLIS_IN_DAY = 1000 * 60 * 60 * 24;  
  long endInstant = endDate.getTimeInMillis();  
  int presumedDays = 
    (int) ((endInstant - startDate.getTimeInMillis()) / MILLIS_IN_DAY);  
  Calendar cursor = (Calendar) startDate.clone();  
  cursor.add(Calendar.DAY_OF_YEAR, presumedDays);  
  long instant = cursor.getTimeInMillis();  
  if (instant == endInstant)  
    return presumedDays;

  final int step = instant < endInstant ? 1 : -1;  
  do {  
    cursor.add(Calendar.DAY_OF_MONTH, step);  
    presumedDays += step;  
  } while (cursor.getTimeInMillis() != endInstant);  
  return presumedDays;  
}
 23
Author: Mad_troll,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2013-04-23 18:55:44

Java.czas

W Javie 8 i późniejszych używaj Javy .ramy czasowe (Tutorial ).

Duration

The Duration Klasa reprezentuje rozpiętość czasu jako liczbę sekund plus ułamkową sekundę. Może liczyć dni, godziny, minuty i sekundy.

ZonedDateTime now = ZonedDateTime.now();
ZonedDateTime oldDate = now.minusDays(1).minusMinutes(10);
Duration duration = Duration.between(oldDate, now);
System.out.println(duration.toDays());

ChronoUnit

Jeśli potrzebujesz tylko liczby dni, alternatywnie możesz użyć ChronoUnit enum . Zauważ, że metody obliczeniowe zwracają long zamiast int.

long days = ChronoUnit.DAYS.between( then, now );
 15
Author: Vitalii Fedorenko,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2016-06-14 15:38:38

To zależy od tego, co zdefiniujesz jako różnicę. Aby porównać dwie daty o północy można zrobić.

long day1 = ...; // in milliseconds.
long day2 = ...; // in milliseconds.
long days = (day2 - day1) / 86400000;
 13
Author: Peter Lawrey,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2010-07-29 19:10:07
import java.util.Calendar;
import java.util.Date;

public class Main {
    public static long calculateDays(String startDate, String endDate)
    {
        Date sDate = new Date(startDate);
        Date eDate = new Date(endDate);
        Calendar cal3 = Calendar.getInstance();
        cal3.setTime(sDate);
        Calendar cal4 = Calendar.getInstance();
        cal4.setTime(eDate);
        return daysBetween(cal3, cal4);
    }

    public static void main(String[] args) {
        System.out.println(calculateDays("2012/03/31", "2012/06/17"));

    }

    /** Using Calendar - THE CORRECT WAY**/
    public static long daysBetween(Calendar startDate, Calendar endDate) {
        Calendar date = (Calendar) startDate.clone();
        long daysBetween = 0;
        while (date.before(endDate)) {
            date.add(Calendar.DAY_OF_MONTH, 1);
            daysBetween++;
        }
        return daysBetween;
    }
}
 13
Author: Soumyarup Dasgupta,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2012-09-27 05:26:54

Rozwiązanie wykorzystujące różnicę między milisekundami czasu, z prawidłowym zaokrągleniem dla dat DST:

public static long daysDiff(Date from, Date to) {
    return daysDiff(from.getTime(), to.getTime());
}

public static long daysDiff(long from, long to) {
    return Math.round( (to - from) / 86400000D ); // 1000 * 60 * 60 * 24
}

Jedna uwaga: oczywiście, daty MUSZĄ BYĆ w jakiejś strefie czasowej.

Ważny kod:

Math.round( (to - from) / 86400000D )

Jeśli nie chcesz rundy, możesz użyć dat UTC,

 9
Author: angelcervera,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2013-03-02 09:58:07

Ilustracja problemu: (mój kod oblicza deltę w tygodniach, ale ten sam problem dotyczy Delty w dniach)

Oto bardzo rozsądnie wyglądająca implementacja:

public static final long MILLIS_PER_WEEK = 7L * 24L * 60L * 60L * 1000L;

static public int getDeltaInWeeks(Date latterDate, Date earlierDate) {
    long deltaInMillis = latterDate.getTime() - earlierDate.getTime();
    int deltaInWeeks = (int)(deltaInMillis / MILLIS_PER_WEEK);
    return deltaInWeeks; 
}

Ale ten test się nie powiedzie:

public void testGetDeltaInWeeks() {
    delta = AggregatedData.getDeltaInWeeks(dateMar09, dateFeb23);
    assertEquals("weeks between Feb23 and Mar09", 2, delta);
}

Powodem jest:

Mon Mar 09 00: 00: 00 EDT 2009 = 1.236.571.200.000
Mon Feb 23 00: 00: 00 EST 2009 = 1,235,365,200,000
Milisperweek = 604 800 000
Tak Więc,
(Mar09-Feb23) / Milisperweek =
1,206,000,000 / 604,800,000 = 1.994...

Ale każdy, kto spojrzy na kalendarz, zgodzi się, że odpowiedź to 2.
 4
Author: KennethB,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2012-08-20 10:26:04

Używam tej funkcji:

DATEDIFF("31/01/2016", "01/03/2016") // me return 30 days

Moja funkcja:

import java.util.Date;

public long DATEDIFF(String date1, String date2) {
        long MILLISECS_PER_DAY = 24 * 60 * 60 * 1000;
        long days = 0l;
        SimpleDateFormat format = new SimpleDateFormat("dd/MM/yyyy"); // "dd/MM/yyyy HH:mm:ss");

        Date dateIni = null;
        Date dateFin = null;        
        try {       
            dateIni = (Date) format.parse(date1);
            dateFin = (Date) format.parse(date2);
            days = (dateFin.getTime() - dateIni.getTime())/MILLISECS_PER_DAY;                        
        } catch (Exception e) {  e.printStackTrace();  }   

        return days; 
     }
 3
Author: cesin,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2013-05-24 18:09:10

Spójrz na getFragmentInDays metody w tej klasie Apache commons-lang DateUtils.

 2
Author: ccpizza,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2013-03-25 16:30:50

Na podstawie odpowiedzi @Mad_Troll opracowałem tę metodę.

Przeprowadziłem z nim około 30 przypadków testowych, jest to jedyna metoda, która poprawnie obsługuje fragmenty czasu podrzędnego.

Przykład: jeśli zdasz teraz & now + 1 milisekundę, która jest nadal tego samego dnia. Wykonywanie 1-1-13 23:59:59.098 do 1-1-13 23:59:59.099 zwraca 0 dni, poprawnie; przypisanie innych metod tutaj nie zrobi tego poprawnie.

Warto zauważyć, że nie obchodzi go, w jaki sposób je umieścić, jeśli Data zakończenia jest przed datą rozpoczęcia będzie odliczać wstecz.

/**
 * This is not quick but if only doing a few days backwards/forwards then it is very accurate.
 *
 * @param startDate from
 * @param endDate   to
 * @return day count between the two dates, this can be negative if startDate is after endDate
 */
public static long daysBetween(@NotNull final Calendar startDate, @NotNull final Calendar endDate) {

    //Forwards or backwards?
    final boolean forward = startDate.before(endDate);
    // Which direction are we going
    final int multiplier = forward ? 1 : -1;

    // The date we are going to move.
    final Calendar date = (Calendar) startDate.clone();

    // Result
    long daysBetween = 0;

    // Start at millis (then bump up until we go back a day)
    int fieldAccuracy = 4;
    int field;
    int dayBefore, dayAfter;
    while (forward && date.before(endDate) || !forward && endDate.before(date)) {
        // We start moving slowly if no change then we decrease accuracy.
        switch (fieldAccuracy) {
            case 4:
                field = Calendar.MILLISECOND;
                break;
            case 3:
                field = Calendar.SECOND;
                break;
            case 2:
                field = Calendar.MINUTE;
                break;
            case 1:
                field = Calendar.HOUR_OF_DAY;
                break;
            default:
            case 0:
                field = Calendar.DAY_OF_MONTH;
                break;
        }
        // Get the day before we move the time, Change, then get the day after.
        dayBefore = date.get(Calendar.DAY_OF_MONTH);
        date.add(field, multiplier);
        dayAfter = date.get(Calendar.DAY_OF_MONTH);

        // This shifts lining up the dates, one field at a time.
        if (dayBefore == dayAfter && date.get(field) == endDate.get(field))
            fieldAccuracy--;
        // If day has changed after moving at any accuracy level we bump the day counter.
        if (dayBefore != dayAfter) {
            daysBetween += multiplier;
        }
    }
    return daysBetween;
}

możesz usunąć @NotNull adnotacje, są one używane przez Intellij do analizy kodu w locie

 2
Author: Chris.Jenkins,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2013-10-15 11:27:42

Mówisz, że "działa dobrze w samodzielnym programie", ale otrzymujesz "niezwykłe wartości różnicy", gdy "włączysz to do mojej logiki, aby odczytać z raportu". Sugeruje to, że Twój raport ma pewne wartości, dla których nie działa poprawnie, a Twój samodzielny program nie ma tych wartości. Zamiast samodzielnego programu proponuję przypadek testowy. Napisz przypadek testowy tak samo jak samodzielny program, podklasowany z klasy testcase Junita. Teraz możesz uruchomić bardzo konkretny przykład, wiedząc, jakiej wartości oczekujesz (i nie podawaj jej dzisiaj dla wartości testowej, ponieważ dziś zmienia się w czasie). Jeśli umieścisz wartości użyte w samodzielnym programie, twoje testy prawdopodobnie przejdą. To świetnie. chcesz, żeby te sprawy działały. Teraz dodaj wartość z raportu, który nie działa dobrze. Twój nowy test prawdopodobnie zawiedzie. Dowiedz się, dlaczego zawodzi, napraw to i przejdź do Greena(wszystkie testy przechodzą). Przeprowadź raport. Zobacz co jeszcze jest zepsute; napisz test; zrób to pasuję. Wkrótce przekonasz się, że Twój raport działa.

 1
Author: Carl Manaster,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2010-07-21 14:03:58

Sto linijek kodu dla tej podstawowej funkcji???

Prosta metoda:

protected static int calculateDayDifference(Date dateAfter, Date dateBefore){
    return (int)(dateAfter.getTime()-dateBefore.getTime())/(1000 * 60 * 60 * 24); 
    // MILLIS_IN_DAY = 1000 * 60 * 60 * 24;
}
 1
Author: joro,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2014-08-12 09:43:14
public static int getDifferenceIndays(long timestamp1, long timestamp2) {
    final int SECONDS = 60;
    final int MINUTES = 60;
    final int HOURS = 24;
    final int MILLIES = 1000;
    long temp;
    if (timestamp1 < timestamp2) {
        temp = timestamp1;
        timestamp1 = timestamp2;
        timestamp2 = temp;
    }
    Calendar startDate = Calendar.getInstance(TimeZone.getDefault());
    Calendar endDate = Calendar.getInstance(TimeZone.getDefault());
    endDate.setTimeInMillis(timestamp1);
    startDate.setTimeInMillis(timestamp2);
    if ((timestamp1 - timestamp2) < 1 * HOURS * MINUTES * SECONDS * MILLIES) {
        int day1 = endDate.get(Calendar.DAY_OF_MONTH);
        int day2 = startDate.get(Calendar.DAY_OF_MONTH);
        if (day1 == day2) {
            return 0;
        } else {
            return 1;
        }
    }
    int diffDays = 0;
    startDate.add(Calendar.DAY_OF_MONTH, diffDays);
    while (startDate.before(endDate)) {
        startDate.add(Calendar.DAY_OF_MONTH, 1);
        diffDays++;
    }
    return diffDays;
}
 1
Author: user1091978,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2014-12-24 17:34:57

ThreeTen-Extra

Odpowiedź Vitalii Fedorenko jest poprawna, opisując jak wykonać te obliczenia w nowoczesny sposób za pomocą Javy.czas klasy (Duration & ChronoUnit) wbudowany w Javę 8 i nowszą (oraz Z powrotem przeniesiony do Javy 6 i 7 i do Androida ).

Days

Jeśli używasz rutynowo kilku dni w kodzie, możesz zastąpić zwykłe liczby całkowite za pomocą klasy. Na Days klasa może można go znaleźć w projekcie ThreeTen-Extra , rozszerzeniu Javy.czas i poligon dla ewentualnych przyszłych dodatków do Javy.czas. Klasa Days zapewnia bezpieczny dla typu sposób reprezentowania liczby dni w aplikacji. Klasa zawiera wygodne stałe dla ZERO oraz ONE.

Biorąc pod uwagę stare przestarzałe java.util.Date obiektów w pytaniu, najpierw przekonwertować je na nowoczesne java.time.Instant obiektów. Stare klasy date-time mają nowo dodano metody ułatwiające konwersję do Javy.czas, taki java.util.Date::toInstant.

Instant start = utilDateStart.toInstant(); // Inclusive.
Instant stop = utilDateStop.toInstant();  // Exclusive.

Przekazać oba obiekty Instant do metody Fabrycznej dla org.threeten.extra.Days.

W obecnej implementacji (2016-06) jest to wrapper wywołujący java.time.temporal.ChronoUnit.DAYS.between, przeczytaj ChronoUnit Klasa doc dla szczegółów. Dla jasności: wszystkie wielkie litery DAYS są w enum ChronoUnit, podczas gdy initial-cap Days jest klasą z ThreeTen-Extra.

Days days = Days.between( start , stop );

Możesz przekazać te Days obiekty wokół własnego kodu. Możesz serializacja Do ciągu znaków w standardowym formacie ISO 8601 przez wywołanie toString. Format PnD używa P do oznaczania początku i D oznacza "dni", z liczbą dni pomiędzy nimi. Zarówno java.klasy czasu i ThreeTen-Extra domyślnie używają tych standardowych formatów podczas generowania i parsowania łańcuchów reprezentujących wartości daty i czasu.

String output = days.toString();

P3D

Days days = Days.parse( "P3D" );  
 1
Author: Basil Bourque,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2017-05-23 12:09:17

Ten kod oblicza dni pomiędzy dwoma łańcuchami daty:

    static final long MILLI_SECONDS_IN_A_DAY = 1000 * 60 * 60 * 24;
    static final String DATE_FORMAT = "dd-MM-yyyy";
    public long daysBetween(String fromDateStr, String toDateStr) throws ParseException {
    SimpleDateFormat format = new SimpleDateFormat(DATE_FORMAT);
    Date fromDate;
    Date toDate;
    fromDate = format.parse(fromDateStr);
    toDate = format.parse(toDateStr);
    return (toDate.getTime() - fromDate.getTime()) / MILLI_SECONDS_IN_A_DAY;
}
 0
Author: Kayvan Tehrani,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2014-08-16 09:45:46

Jeśli szukasz rozwiązania, które zwróci odpowiednią liczbę lub dni między np. 11/30/2014 23:59 i {[2] }Oto rozwiązanie wykorzystujące czas Joda.

private int getDayDifference(long past, long current) {
    DateTime currentDate = new DateTime(current);
    DateTime pastDate = new DateTime(past);
    return currentDate.getDayOfYear() - pastDate.getDayOfYear();
} 

Ta implementacja zwróci 1 jako różnicę w dniach. Większość zamieszczonych tu rozwiązań oblicza różnicę w milisekundach między dwiema datami. Oznacza to, że 0 zostanie zwrócona, ponieważ różnica między tymi dwoma datami wynosi tylko 2 minuty.

 0
Author: tomrozb,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2014-12-03 16:02:06

Już o tym pisałem. Jest to repost z obliczający różnicę między dwoma instancjami Java date .

public int getDiffernceInDays(long timeAfter, long timeBefore) {
    Calendar calendarAfter = Calendar.getInstance();
    calendarAfter.setTime(new Date(timeAfter));

    Calendar calendarNewAfter = Calendar.getInstance();
    calendarNewAfter.set(calendarAfter.get(Calendar.YEAR), calendarAfter.get(Calendar.MONTH), calendarAfter.get(Calendar.DAY_OF_MONTH));

    Calendar calendarBefore = Calendar.getInstance();
    calendarBefore.setTime(new Date(timeBefore));

    Calendar calendarNewBefore = Calendar.getInstance();
    calendarNewBefore.set(calendarBefore.get(Calendar.YEAR), calendarBefore.get(Calendar.MONTH), calendarBefore.get(Calendar.DAY_OF_MONTH));

    return (int) ((calendarNewAfter.getTime().getTime() - calendarNewBefore.getTime().getTime()) / (24 * 60 * 60 * 1000));
}
 0
Author: M. S.,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2017-05-23 12:09:17

Powinieneś używać biblioteki czasu Joda, ponieważ Java Util date czasami zwraca błędne wartości.

Joda vs Java Util Date

Na przykład dni między dniem wczorajszym (dd-mm-RRRR, 12-07-2016) a pierwszym dniem roku w 1957 r. (dd-mm-RRRR, 01-01-1957):

public class Main {

public static void main(String[] args) {
    SimpleDateFormat format = new SimpleDateFormat("dd-MM-yyyy");

    Date date = null;
    try {
        date = format.parse("12-07-2016");
    } catch (ParseException e) {
        e.printStackTrace();
    }

    //Try with Joda - prints 21742
    System.out.println("This is correct: " + getDaysBetweenDatesWithJodaFromYear1957(date));
    //Try with Java util - prints 21741
    System.out.println("This is not correct: " + getDaysBetweenDatesWithJavaUtilFromYear1957(date));    
}


private static int getDaysBetweenDatesWithJodaFromYear1957(Date date) {
    DateTime jodaDateTime = new DateTime(date);
    DateTimeFormatter formatter = DateTimeFormat.forPattern("dd-MM-yyyy");
    DateTime y1957 = formatter.parseDateTime("01-01-1957");

    return Days.daysBetween(y1957 , jodaDateTime).getDays();
}

private static long getDaysBetweenDatesWithJavaUtilFromYear1957(Date date) {
    SimpleDateFormat format = new SimpleDateFormat("dd-MM-yyyy");

    Date y1957 = null;
    try {
        y1957 = format.parse("01-01-1957");
    } catch (ParseException e) {
        e.printStackTrace();
    }

    return TimeUnit.DAYS.convert(date.getTime() - y1957.getTime(), TimeUnit.MILLISECONDS);
}
Więc naprawdę radzę ci korzystać z biblioteki czasu Joda.
 0
Author: Šime Tokić,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2016-07-13 19:30:02

Zrobiłem to w ten sposób. to proste:)

Date d1 = jDateChooserFrom.getDate();
Date d2 = jDateChooserTo.getDate();

Calendar day1 = Calendar.getInstance();
day1.setTime(d1);

Calendar day2 = Calendar.getInstance();
day2.setTime(d2);

int from = day1.get(Calendar.DAY_OF_YEAR);
int to = day2.get(Calendar.DAY_OF_YEAR);

int difference = to-from;
 -6
Author: Dayadra Lakmal,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2013-10-08 03:28:18