[英]How do I get difference between two dates in android with millisec?
My SimpleDateFormat format is "HH:mm:ss.SSS"我的 SimpleDateFormat 格式是“HH:mm:ss.SSS”
My example time: "00:01:20.442"我的示例时间:“00:01:20.442”
How to get (extract) milliseconds 442 to string?如何获取(提取)毫秒442到字符串?
I found code:我找到了代码:
long diff = date1.getTime() - date2.getTime();
long mseconds = ?????????;
long seconds = diff / 1000;
long minutes = seconds / 60;
long hours = minutes / 60;
long days = hours / 24;
System.out.println("Milliseconds : "+ String.valueOf(mseconds)); System.out.println("毫秒:"+ String.valueOf(mseconds));
PS I'm use API 19 (Adroid 4.4.2) PS 我使用 API 19 (Adroid 4.4.2)
You take the remainder of dividing by 1000, using the remainder operator :使用余数运算符,您可以得到除以 1000 的余数:
long mseconds = diff % 1000;
But note that the milliseconds value you've asked for (442) doesn't match what you're doing to get seconds
, minutes
, etc. In seconds
, you'll get the total number of seconds between the dates, which could be in the hundreds of thousands depending on the dates, not just 0-59.但请注意,您要求的毫秒值 (442) 与您为获取
seconds
、 minutes
等所做的不匹配。以seconds
,您将获得日期之间的总秒数,这可能是在数十万取决于日期,而不仅仅是 0-59。
If the goal is to get days, hours (within the day), minutes (within the hour), etc., then:如果目标是获得天、小时(一天内)、分钟(一小时内)等,那么:
long mseconds = diff % 1000;
long seconds = (diff / 1000) % 60;
long minutes = (seconds / 60) % 60;
long hours = (minutes / 60) % 24;
long days = hours / 24;
Using the Joda Time
library (which in my opinion should be in every project that uses time):使用
Joda Time
库(在我看来应该在每个使用时间的项目中):
final long millis = DateTime.parse("00:01:20.442", DateTimeFormat.forPattern("HH:mm:ss.SSS")).getMillisOfSecond();
assertEquals(442, millis);
Or, if you want all of them:或者,如果您想要所有这些:
final DateTime dt = DateTime.parse("00:01:20.442", DateTimeFormat.forPattern("HH:mm:ss.SSS"));
final long millis = dt.getMillisOfSecond(); //442
final long second = dt.getSecondOfMinute(); //20
final long min = dt.getMinuteOfHour(); //1
final long hour = dt.getHourOfDay(); //0
Why don't you simply split the String by .
为什么不简单地将字符串拆分为
.
and use the second element?并使用第二个元素? Like:
喜欢:
long millis = Long.parseLong(dateStr.split(".")[1]);
Where dateStr
is a String
of form HH:mm:ss.SSS
.其中
dateStr
是HH:mm:ss.SSS
形式的String
。
It is much better solution than using a 3rd party library for simple task.这比使用 3rd 方库来完成简单任务要好得多。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.