Android różnica między dwoma datami

Mam dwie daty:

String date_1="yyyyMMddHHmmss";
String date_2="yyyyMMddHHmmss";

Chcę wydrukować różnicę w stylu:

2d 3h 45m
Jak mogę to zrobić? Dzięki!
Author: Vini.g.fer, 2014-01-22

12 answers

DateTimeUtils obj = new DateTimeUtils();
SimpleDateFormat simpleDateFormat = new SimpleDateFormat("dd/M/yyyy hh:mm:ss");

try {
    Date date1 = simpleDateFormat.parse("10/10/2013 11:30:10");
    Date date2 = simpleDateFormat.parse("13/10/2013 20:35:55");

    obj.printDifference(date1, date2);

} catch (ParseException e) {
    e.printStackTrace();
}

//1 minute = 60 seconds
//1 hour = 60 x 60 = 3600
//1 day = 3600 x 24 = 86400
public void printDifference(Date startDate, Date endDate) { 
    //milliseconds
    long different = endDate.getTime() - startDate.getTime();

    System.out.println("startDate : " + startDate);
    System.out.println("endDate : "+ endDate);
    System.out.println("different : " + different);

    long secondsInMilli = 1000;
    long minutesInMilli = secondsInMilli * 60;
    long hoursInMilli = minutesInMilli * 60;
    long daysInMilli = hoursInMilli * 24;

    long elapsedDays = different / daysInMilli;
    different = different % daysInMilli;

    long elapsedHours = different / hoursInMilli;
    different = different % hoursInMilli;

    long elapsedMinutes = different / minutesInMilli;
    different = different % minutesInMilli;

    long elapsedSeconds = different / secondsInMilli;

    System.out.printf(
        "%d days, %d hours, %d minutes, %d seconds%n", 
        elapsedDays, elapsedHours, elapsedMinutes, elapsedSeconds);
}

Out put is:

startDate : Thu Oct 10 11:30:10 SGT 2013
endDate : Sun Oct 13 20:35:55 SGT 2013
different : 291945000
3 days, 9 hours, 5 minutes, 45 seconds
 118
Author: Digvesh Patel,
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-07-15 12:31:30

To działa i konwertuje na String jako Bonus;)

protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

    setContentView(R.layout.activity_main);

    try {
        //Dates to compare
        String CurrentDate=  "09/24/2015";
        String FinalDate=  "09/26/2015";

        Date date1;
        Date date2;

        SimpleDateFormat dates = new SimpleDateFormat("MM/dd/yyyy");

        //Setting dates
        date1 = dates.parse(CurrentDate);
        date2 = dates.parse(FinalDate);

        //Comparing dates
        long difference = Math.abs(date1.getTime() - date2.getTime());
        long differenceDates = difference / (24 * 60 * 60 * 1000);

        //Convert long to String
        String dayDifference = Long.toString(differenceDates);

        Log.e("HERE","HERE: " + dayDifference);

    } catch (Exception exception) {
        Log.e("DIDN'T WORK", "exception " + exception);
    }
}
 8
Author: TheVinceble,
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-07-15 12:34:38

To da Ci różnicę w miesiącach

long milliSeconds1 = calendar1.getTimeInMillis();
long milliSeconds2 = calendar2.getTimeInMillis();
long periodSeconds = (milliSeconds2 - milliSeconds1) / 1000;
long elapsedDays = periodSeconds / 60 / 60 / 24;

System.out.println(String.format("%d months", elapsedDays/30));
 5
Author: Swap-IOS-Android,
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-07-15 12:35:13
Date userDob = new SimpleDateFormat("yyyy-MM-dd").parse(dob);
Date today = new Date();
long diff =  today.getTime() - userDob.getTime();
int numOfDays = (int) (diff / (1000 * 60 * 60 * 24));
int hours = (int) (diff / (1000 * 60 * 60));
int minutes = (int) (diff / (1000 * 60));
int seconds = (int) (diff / (1000));
 3
Author: Nilesh Savaliya,
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-07-15 12:35:34
DateTime start = new DateTime(2013, 10, 20, 5, 0, 0, Locale);
DateTime end = new DateTime(2013, 10, 21, 13, 0, 0, Locale);
Days.daysBetween(start.toLocalDate(), end.toLocalDate()).getDays()

Zwraca liczbę dni pomiędzy podanymi datami, gdzie {[1] } pochodzi z biblioteki joda

 1
Author: subrahmanyam boyapati,
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-09-28 08:59:05

Short & Sweet:

/**
 * Get a diff between two dates
 *
 * @param oldDate the old date
 * @param newDate the new date
 * @return the diff value, in the days
 */
public static long getDateDiff(SimpleDateFormat format, String oldDate, String newDate) {
    try {
        return TimeUnit.DAYS.convert(format.parse(newDate).getTime() - format.parse(oldDate).getTime(), TimeUnit.MILLISECONDS);
    } catch (Exception e) {
        e.printStackTrace();
        return 0;
    }
}

Użycie:

int dateDifference = (int) getDateDiff(new SimpleDateFormat("dd/MM/yyyy"), "29/05/2017", "31/05/2017");
System.out.println("dateDifference: " + dateDifference);

Wyjście:

dateDifference: 2
 1
Author: Meet,
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-29 06:45:04

Za pomocą tej metody można obliczyć różnicę czasu w milisekundach i uzyskać wyniki w sekundach, minutach, godzinach, dniach, miesiącach i latach.

Możesz pobrać klasę stąd: DateTimeDifference GitHub Link

  • prosty w użyciu
long currentTime = System.currentTimeMillis();
long previousTime = (System.currentTimeMillis() - 864000000); //10 days ago

Log.d("DateTime: ", "Difference With Second: " + AppUtility.DateTimeDifference(currentTime, previousTime, AppUtility.TimeDifference.SECOND));
Log.d("DateTime: ", "Difference With Minute: " + AppUtility.DateTimeDifference(currentTime, previousTime, AppUtility.TimeDifference.MINUTE));
  • Możesz porównać poniższy przykład
if(AppUtility.DateTimeDifference(currentTime, previousTime, AppUtility.TimeDifference.MINUTE) > 100){
    Log.d("DateTime: ", "There are more than 100 minutes difference between two dates.");
}else{
    Log.d("DateTime: ", "There are no more than 100 minutes difference between two dates.");
}
 1
Author: A. Batuhan Özkaya,
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-08-15 20:36:11

Kiedy używasz Date() do obliczenia różnicy godzin jest konieczne skonfiguruj SimpleDateFormat() W UTC w przeciwnym razie otrzymasz godzinę błędu ze względu na czas oszczędzania światła dziennego.

 0
Author: user3812123,
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-15 04:25:10

Używam tego: wysyłanie daty rozpoczęcia i zakończenia w milisekundzie

public int GetDifference(long start,long end){
    Calendar cal = Calendar.getInstance();
    cal.setTimeInMillis(start);
    int hour = cal.get(Calendar.HOUR_OF_DAY);
    int min = cal.get(Calendar.MINUTE);
    long t=(23-hour)*3600000+(59-min)*60000;

    t=start+t;

    int diff=0;
    if(end>t){
        diff=(int)((end-t)/ TimeUnit.DAYS.toMillis(1))+1;
    }

    return  diff;
}
 0
Author: ahmad dehghan,
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-01-09 05:13:18

Można uogólnić to do funkcji, która pozwala wybrać format wyjściowy

private String substractDates(Date date1, Date date2, SimpleDateFormat format) {
    long restDatesinMillis = date1.getTime()-date2.getTime();
    Date restdate = new Date(restDatesinMillis);

    return format.format(restdate);
}

Teraz jest proste wywołanie funkcji jak ta, różnica w godzinach, minutach i sekundach:

SimpleDateFormat formater = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

try {
    Date date1 = formater.parse(dateEnd);
    Date date2 = formater.parse(dateInit);

    String result = substractDates(date1, date2, new SimpleDateFormat("HH:mm:ss"));

    txtTime.setText(result);
} catch (ParseException e) {
    e.printStackTrace();
}
 0
Author: Exensor,
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-07-15 12:37:16

Oto współczesna odpowiedź. Jest to dobre dla każdego, kto korzysta z Javy 8 lub nowszej (która nie jest jeszcze dostępna dla większości telefonów z Androidem) lub jest zadowolony z zewnętrznej biblioteki.

    String date1 = "20170717141000";
    String date2 = "20170719175500";

    DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyyMMddHHmmss");
    Duration diff = Duration.between(LocalDateTime.parse(date1, formatter), 
                                     LocalDateTime.parse(date2, formatter));

    if (diff.isZero()) {
        System.out.println("0m");
    } else {
        long days = diff.toDays();
        if (days != 0) {
            System.out.print("" + days + "d ");
            diff = diff.minusDays(days);
        }
        long hours = diff.toHours();
        if (hours != 0) {
            System.out.print("" + hours + "h ");
            diff = diff.minusHours(hours);
        }
        long minutes = diff.toMinutes();
        if (minutes != 0) {
            System.out.print("" + minutes + "m ");
            diff = diff.minusMinutes(minutes);
        }
        long seconds = diff.getSeconds();
        if (seconds != 0) {
            System.out.print("" + seconds + "s ");
        }
        System.out.println();
    }

To drukuje

2d 3h 45m 

Moim zdaniem zaletą nie jest to, że jest krótszy (niewiele), ale pozostawienie obliczeń w bibliotece standardowej jest mniej błędem i daje jaśniejszy kod. Są to wielkie zalety. Czytelnik nie jest obciążony rozpoznaniem stałych jak 24, 60 i 1000 oraz sprawdzenie, czy są one prawidłowo używane.

Używam nowoczesnego Java date & time API (opisanego w JSR-310 i znanego również pod tą nazwą). Aby użyć tego na Androidzie, Pobierz ThreeTenABP, Zobacz to pytanie: Jak używać ThreeTenABP w projekcie Android . Aby użyć go z innymi Java 6 lub 7, Pobierz Threeten Backport. Z Javą 8 i nowszą jest wbudowany.

Z Javą 9 będzie jeszcze trochę łatwiej, ponieważ klasa Duration jest rozszerzona o metody, które dają ty część dni, część godzin, część minut i część sekund osobno, więc nie potrzebujesz odejmowania. Zobacz przykład w moja odpowiedź tutaj .

 0
Author: Ole V.V.,
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-07-18 14:38:34

Trochę zaaranżowałem. To działa świetnie.

@SuppressLint("SimpleDateFormat") SimpleDateFormat simpleDateFormat = new SimpleDateFormat("dd MM yyyy");
    Date date = new Date();
    String dateOfDay = simpleDateFormat.format(date);

    String timeofday = android.text.format.DateFormat.format("HH:mm:ss", new Date().getTime()).toString();

    @SuppressLint("SimpleDateFormat") SimpleDateFormat dateFormat = new SimpleDateFormat("dd MM yyyy hh:mm:ss");
    try {
        Date date1 = dateFormat.parse(06 09 2018 + " " + 10:12:56);
        Date date2 = dateFormat.parse(dateOfDay + " " + timeofday);

        printDifference(date1, date2);

    } catch (ParseException e) {
        e.printStackTrace();
    }

@SuppressLint("SetTextI18n")
private void printDifference(Date startDate, Date endDate) {
    //milliseconds
    long different = endDate.getTime() - startDate.getTime();

    long secondsInMilli = 1000;
    long minutesInMilli = secondsInMilli * 60;
    long hoursInMilli = minutesInMilli * 60;
    long daysInMilli = hoursInMilli * 24;

    long elapsedDays = different / daysInMilli;
    different = different % daysInMilli;

    long elapsedHours = different / hoursInMilli;
    different = different % hoursInMilli;

    long elapsedMinutes = different / minutesInMilli;
    different = different % minutesInMilli;

    long elapsedSeconds = different / secondsInMilli;

Toast.makeText(context, elapsedDays + " " + elapsedHours + " " + elapsedMinutes + " " + elapsedSeconds, Toast.LENGTH_SHORT).show();
}
 0
Author: Trk,
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
2018-09-09 09:25:15