Serjaru
Serjaru

Reputation: 87

How do I get difference between two dates in android with millisec?

My SimpleDateFormat format is "HH:mm:ss.SSS"

My example time: "00:01:20.442"

How to get (extract) milliseconds 442 to string?

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));

P.S. I'm use API 19 (Adroid 4.4.2)

Upvotes: 0

Views: 169

Answers (3)

Malwinder Singh
Malwinder Singh

Reputation: 7070

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.

It is much better solution than using a 3rd party library for simple task.

Upvotes: 0

PPartisan
PPartisan

Reputation: 8231

Using the Joda Time library (which in my opinion should be in every project that uses 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

Upvotes: 1

T.J. Crowder
T.J. Crowder

Reputation: 1075815

You take the remainder of dividing by 1000, using the remainder operator:

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.

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;

Upvotes: 1

Related Questions