【问题标题】:How to get the difference between 2 times in android如何在android中获得2次之间的差异
【发布时间】:2012-04-30 20:16:58
【问题描述】:

我想找出当前系统时间和插入数据和时间String之间的差异。我试过这个:

 try {

            String strFileDate = "2012-04-19 15:15:00";
            DateFormat formatter2 = new SimpleDateFormat("yyyy-mm-dd hh:mm:ss");
            Date date = formatter2.parse(strFileDate);
            long difference = date.getTime() - System.currentTimeMillis();
            Calendar calendar = Calendar.getInstance();
            calendar.setTimeInMillis(difference);
            Toast.makeText(getBaseContext(),
                    formatter2.format(calendar.getTime()), Toast.LENGTH_LONG)
                    .show();
        } catch (Exception e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } 

但它没有给我正确的结果。我做得对吗?

更新

我尝试关注 ::

String strFileDate = "2012-04-19 15:15:00";
            DateFormat formatter2 = new SimpleDateFormat("yyyy-mm-dd hh:mm:ss");
            Date date = formatter2.parse(strFileDate);
            long diffInMs = date.getTime()
                    - new Date(System.currentTimeMillis()).getTime();

            long diffInSec = TimeUnit.MILLISECONDS.toSeconds(diffInMs);

            long hour = diffInSec / (1000 * 60 * 60);
            double minutes = diffInSec / (1000 * 60);
            // long diffInHour = TimeUnit.to(diffInMs);

            Toast.makeText(getBaseContext(),
                    "left time is :: " + hour + ":" + minutes,
                    Toast.LENGTH_LONG).show();

输出:: 剩余时间是:: -2 : -131.0

更新(2012 年 4 月 20 日)

try {
            Date dt = new Date();
            String strFileDate = "2012-04-20 13:10:00";
            DateFormat formatter2 = new SimpleDateFormat("yyyy-mm-dd hh:mm:ss");
            Date date = formatter2.parse(strFileDate);
            String s = getTimeDiff(dt, date);
            Log.i("Date is :: >>> ", s);
        } catch (Exception e) {
            e.printStackTrace();
        }
 public String getTimeDiff(Date dateOne, Date dateTwo) {
        String diff = "";
        long timeDiff = Math.abs(dateOne.getTime() - dateTwo.getTime());
        diff = String.format("%d hour(s) %d min(s)", TimeUnit.MILLISECONDS.toHours(timeDiff),
                TimeUnit.MILLISECONDS.toMinutes(timeDiff) - TimeUnit.HOURS.toMinutes(TimeUnit.MILLISECONDS.toHours(timeDiff)));
        return diff;

}

输出:: 04-20 12:48:06.629: 信息/日期是 :: >>>(1295): 2183 小时 38 分钟

【问题讨论】:

  • 我想要分钟和小时的时差..
  • 什么不起作用?您希望在 Toast 中看到什么?你对这个 sn-p 有什么期望?日历日历 = Calendar.getInstance(); calendar.setTimeInMillis(差异);请提供更多详细信息。
  • @krishnakumarp 我已经更新了我的代码,请检查一下
  • 你应该替换 long diffInMs = date.getTime() - new Date(System.currentTimeMillis()).getTime(); with long diffInMs = new Date(System.currentTimeMillis()).getTime() - date.getTime();

标签: java android calendar


【解决方案1】:

tl;博士

ChronoUnit.MINUTES.between(
    LocalDateTime.parse( "2012-04-19 15:15:00".replace( " " , "T" ) ).atZone( ZoneId.of( "Pacific/Auckland" ) ) ,
    LocalDateTime.parse( "2012-04-19 23:49:00".replace( " " , "T" ) ).atZone( ZoneId.of( "Pacific/Auckland" ) ) 
)

514

时区

您的代码忽略了时区的关键问题。

java.util.Date 类代表 UTC 中的一个时刻。同时,您的输入字符串“2012-04-19 15:15:00”缺少任何时区指示或与 UTC 的偏移量。您必须将该值显式放入预期/所需区域/偏移的上下文中,否则这些遗留类将隐式应用区域/偏移。

java.time

现代方法使用 Java 8 及更高版本中内置的 java.time 类。

您的输入几乎符合标准 ISO 8601 格式。将中间的空格切换为T

String input = "2012-04-19 15:15:00".replace( " " , "T" ) ;  // Convert to ISO 8601 format.

解析为LocalDateTime 对象,因为您的输入缺少区域或偏移量。

LocalDateTime ldt = LocalDateTime.parse( input ) ;

应用您确定用于该输入的区域或偏移量。

OffsetDateTime odt = ldt.atOffset( ZoneOffset.UTC ) ; // Or some other offset.

……或者……

ZoneId z = ZoneId.of( "Africa/Tunis" ) ;
ZonedDateTime zdt = ldt.atZone( z ) ;

如果您希望将两个时刻之间的增量作为时间跨度,而不附加到按小时-分钟-秒缩放的时间线,请计算 Duration

Duration d = Duration.between( start , stop ) ;

类似,但以年-月-日为单位,使用Period。提取 LocalDate 仅日期对象以提供 Period 的工厂方法。

Period p = Period.between( start.toLocalDate() , stop.toLocalDate() ) ;

总耗时

如果您想要单个总经过的分钟数、秒数等,请在 ChronoUnit 枚举上使用 ChronoUnit::between 方法。

long totalMinutes = ChronoUnit.MINUTES.between( start , stop ) ;  // Calculate total number of minutes in entire span of time.

生成字符串

standard ISO 8601 format 中生成一个字符串。只需致电Duration::toStringPeriod::toString

格式为PnYnMnDTnHnMnS,其中P 表示开始,T 将任何年-月-日与任何小时-分钟-秒分开。

String output = d.toString() ;

您可以通过调用各种getter方法来查询零件。

提示:如果您的工作时间跨度如此之大,请将 ThreeTen-Extra 库添加到您的项目中以使用 IntervalLocalDateRange类。


关于java.time

java.time 框架内置于 Java 8 及更高版本中。这些类取代了麻烦的旧 legacy 日期时间类,例如 java.util.DateCalendarSimpleDateFormat

Joda-Time 项目现在位于maintenance mode,建议迁移到java.time 类。

要了解更多信息,请参阅Oracle Tutorial。并在 Stack Overflow 上搜索许多示例和解释。规格为JSR 310

您可以直接与您的数据库交换 java.time 对象。使用符合JDBC 4.2 或更高版本的JDBC driver。不需要字符串,不需要java.sql.* 类。

从哪里获得 java.time 类?

ThreeTen-Extra 项目通过附加类扩展了 java.time。该项目是未来可能添加到 java.time 的试验场。您可以在这里找到一些有用的类,例如IntervalYearWeekYearQuartermore

【讨论】:

    【解决方案2】:
    String strFileDate = "2012-04-19 15:15:00";
    DateFormat formatter2 = new SimpleDateFormat("yyyy-mm-dd hh:mm:ss");
    Date date = formatter2.parse(strFileDate);
    long diffInMs = date.getTime() - new Date(System.currentTimeMillis()).getTime();
    
    
    long diffInSec = TimeUnit.MILLISECONDS.toSeconds(diffInMis);
    
    long diffInHour = TimeUnit.MILLISECONDS.toHours(diffInMis);
    

    使用 TimeUnit 获取秒数。 http://developer.android.com/reference/java/util/concurrent/TimeUnit.html

    已编辑:

    获取TIMEUNIT Code here

    public String getTimeDiff(Date dateOne, Date dateTwo) {
            String diff = "";
            long timeDiff = Math.abs(dateOne.getTime() - dateTwo.getTime());
            diff = String.format("%d hour(s) %d min(s)", TimeUnit.MILLISECONDS.toHours(timeDiff),
                    TimeUnit.MILLISECONDS.toMinutes(timeDiff) - TimeUnit.HOURS.toMinutes(TimeUnit.MILLISECONDS.toHours(timeDiff)));
            return diff;
    }
    

    【讨论】:

    • 你能举出完整的例子吗??
    • 我已经继续使用diffInMs 所以现在告诉我如何将 long 转换为 minuts
    • @hotveryspicy 没有TimeUnit.toMinutes(diff); 任何类型的方法
    • 创建对象然后尝试 TimeUnit mTimeUnit= new TimeUnit(); mTimeUnit.toMinutes(diff);
    • 查看我编辑的答案并下载 Timeunit 的新源代码,android 内置类没有完整的功能。
    【解决方案3】:
        Calendar calendar = Calendar.getInstance();
    calendar.setTime(date.getYear(),date.getMonth(),date.getDay(),date.getHourOFday(),date.getMinutes(),date.getSeconds); // not syntactically right..
    long difference = System.currentTimeMillis()-calendar.getTimeInMillis();
    

    为了得到不同的小时数

    double hour = difference/(1000*60*60);
    double minutes = difference/(1000*60);
    

    【讨论】:

    • 小时让我正常,但分钟不能让我正常
    • @user1343673 .. 查看更新的答案.. 我已经改变了 long difference = System.currentTimeMillis()-calendar.getTimeInMillis();
    【解决方案4】:

    使用 JodaTime 计算周期(时差)。 http://joda-time.sourceforge.net/

    【讨论】:

    【解决方案5】:
    • 你得到什么输出?
    • 您期望什么输出?

    如果您需要此时间(以秒为单位),请参阅 #3960661

    【讨论】:

    • 那就看#6118922 :)
    • @PareshMayani .. 有什么你能容忍的吗.. 你为什么要取笑那些提出幼稚问题的人......我敢打赌,如果你花同样多的时间回答某人的问题,它会帮助了他们,.. 而不是试图在这里搞笑.. 第二次相同的 BMW 评论.. 真可惜...
    • @sandy 仅供参考,此时,这里已经有很多关于“日期/时差”主题的问题/答案。他直接用“顺序”的语言说我想要这个,这个。
    • @PareshMayani .. 那你为什么不粘贴一个链接... 为什么你总是开玩笑... 它不鼓励任何人提问..
    猜你喜欢
    • 2015-04-21
    • 2015-04-16
    • 1970-01-01
    • 1970-01-01
    • 2017-10-07
    • 2016-10-08
    • 1970-01-01
    • 2014-05-14
    • 1970-01-01
    相关资源
    最近更新 更多