简体   繁体   English

如何找到两次之间的差异?

[英]How can I find the difference between the two times?

I get time from the server like this 2018-11-27T09:51:31.832107+00:00 , then I parse the time so OffsetDateTime.parse . 我从这样的服务器那里获取时间2018-11-27T09:51:31.832107+00:00 ,然后我解析时间,所以OffsetDateTime.parse I want to differentiate between the two times OffsetDateTime.now - OffsetDateTime.parse . 我想区分两次OffsetDateTime.now - OffsetDateTime.parse

After subtraction, I have to show the elapsed time in this form: 14 min 12 seconds . 减去后,我必须以这种形式显示经过的时间: 14 min 12 seconds How can I do it right to get a span-of-time? 如何正确获得时间跨度?

It's easy when you know how: 当您知道如何时,这很容易:

// Parse input.
String timeFromServer = "2018-11-27T09:51:31.832107+00:00";
OffsetDateTime odt = OffsetDateTime.parse(timeFromServer);

// Capture the current moment. 
OffsetDateTime now =  OffsetDateTime.now(ZoneOffset.UTC)

// Get the difference
Duration difference = Duration.between(odt,now);

// Extract details: Convert to minutes and seconds
long minutes = difference.toMinutes();
difference = difference.minusMinutes(minutes);
long seconds = difference.getSeconds();

// Format into string in desired form
String formattedDiff = String.format("%d min %d seconds", minutes, seconds);
System.out.println(formattedDiff);

When run now we get a large number of minutes since your example string is from last month. 现在运行时,由于您的示例字符串来自上个月,因此我们需要花费大量时间。

34613 min 38 seconds 34613分钟38秒

The only tricky part is splitting out the minutes and the seconds from the Duration object. 唯一棘手的部分是从Duration对象中拆分分钟和秒。 I take out the minutes first, then subtract them so only the seconds (and smaller) are left. 我先取出分钟,然后减去分钟,只剩下秒(或更短)。 From Java 9 Duration has improved support for getting the individual units of time (see to…Part methods), but I suppose you can't use that on Android yet. 从Java 9开始, Duration改进了对获取单个时间单位的支持(请参阅to…Part方法),但是我想您还不能在Android上使用它。

When it's only for calculating the difference, it doesn't matter which time zone or offset you pass to OffsetDateTime.now . 当仅用于计算差异时,传递给OffsetDateTime.now哪个时区或偏移都没有关系。

You have, in android a mehtod that's called "compare", it may help you, see documentation here : 您在Android中有一个称为“比较”的方法,它可能会对您有所帮助,请参阅此处的文档:

https://developer.android.com/reference/java/time/OffsetDateTime#compareTo(java.time.OffsetDateTime) https://developer.android.com/reference/java/time/OffsetDateTime#compareTo(java.time.OffsetDateTime)

转换两次以毫秒为单位,之后减去第一毫秒第二毫秒,然后格式化结果为口头日期。

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

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