简体   繁体   English

查找带有时区的两个日期之间的时差java / android

[英]Find Diffrence between two dates with time zones java/android

I am trying to find the difference between two java dates with time zone. 我试图找到两个带时区的Java日期之间的差异。 Time zone is GMT.Sever sends the time in this format 2015-04-08 11:17:53 -0400 . 时区为格林尼治标准时间(GMT)。服务器以这种格式发送时间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. 我想找到服务器发送日期格式和当前android系统时间之间的差异(以分钟为单位)。

I am finding the difference like this.c_date is the server date format(2015-04-08 11:17:53 -0400) 我发现这样的区别。c_date是服务器日期格式(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. 当您使用Android时,您很明显不能使用Java 8及其新的时间api,因此我建议使用Joda-time(时间的外部库)。

Example for between calculation: 计算之间的示例:

Seconds.between(startDate, endDate);

More details here: joda 此处有更多详细信息: joda

GMT is the time anywhere in the world. GMT是世界上任何地方的时间。 GMT time code shows the difference between GMT and your local time. GMT时间代码显示GMT与您当地时间之间的时差。 So theoretically , 所以从理论上讲

if your local time code is +/- "GMT 5.00" difference between GMT and your local time = 5 * 60 minutes 如果您当地的时间代码是GMT与您当地的时间之间的+/-“ GMT 5.00” = 5 * 60分钟

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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