简体   繁体   中英

Find Diffrence between two dates with time zones java/android

I am trying to find the difference between two java dates with time zone. Time zone is GMT.Sever sends the time in this format 2015-04-08 11:17:53 -0400 . I want to find the difference (in minutes)between server sent date format and current android system time.

I am finding the difference like this.c_date is the server date format(2015-04-08 11:17:53 -0400)

public static long getDiffrenceBetween(String c_date,String old_date) {
    System.out.println("Cuttent Time   :::"+c_date);
    System.out.println("Saved/Old Time :::"+old_date);

    SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss Z");
    format.setTimeZone(TimeZone.getTimeZone("GMT"));

    Date d1 = null;
    Date d2 = null;
    long min_In_Minutes=0;

    try {
        d1 = format.parse(c_date);
        d2 = format.parse(old_date);

        // in milliseconds
        long diff = d1.getTime() - d2.getTime();
        min_In_Minutes = TimeUnit.MILLISECONDS.toMinutes(diff);

        System.out.println("Diff in Minutes :::"+min_In_Minutes);

        long diffSeconds = diff / (1000 % 60);
        long diffMinutes = diff / (60 * 1000) % 60;
        long diffHours = diff / (60 * 60 * 1000) % 24;
        long diffDays = diff / (24 * 60 * 60 * 1000);

        System.out.println(diffDays + " days, ");
        System.out.println(diffHours + " hours, ");
        System.out.println(diffMinutes + " minutes, ");
        System.out.println(diffSeconds + " seconds.");

    } catch (Exception e) {
        e.printStackTrace();
    }
    return min_In_Minutes;
}

but this is giving negative value in minutes. what is wrong in this method. Please suggest.

Hoping that can find a solution here. Thanks in advance, sharath.

As you are using Android you obiosly cant use Java 8 and its new time api so I would reccomand using Joda-time - an external library for time.

Example for between calculation:

Seconds.between(startDate, endDate);

More details here: joda

GMT is the time anywhere in the world. GMT time code shows the difference between GMT and your local time. So theoretically ,

if your local time code is +/- "GMT 5.00" difference between GMT and your local time = 5 * 60 minutes

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM