0

I have timer for a task. And all the sessions will be added up to each other.

Let's say today user spent 5 minutes

Other day he spent 1 hour, here this one hour will be added to the 5 minutes

and so on..

So it will be the total time in one value..

How can I do this ? Is it by Milliseconds or Date object ?

Swayam
  • 16,294
  • 14
  • 64
  • 102
MBH
  • 16,271
  • 19
  • 99
  • 149

2 Answers2

1

Date is more useful when you are dealing with actual calendar dates.

If you just want to keep track of time intervals/durations, just have a long variable and keep on adding the durations to this.

EDIT : Long.MAX_VALUE is 9,223,372,036,854,775,807. So, you don't really need to worry about the overflow either.

Swayam
  • 16,294
  • 14
  • 64
  • 102
  • i dont deal with any calendar stuff, just how much time did user spent on task or activity, then this time will be always added up to each other, like it can become days or months for later... so long can handle all this ? – MBH Mar 31 '16 at 20:17
  • 1
    Yes, it can. The System returns you the current time in milliseconds in a long variable. That is the number of milliseconds since 1 Jan, 1970. So yeah, if long can handle that, it can surely handle your summation as well! :) – Swayam Mar 31 '16 at 20:22
  • thats convincing, so i will use System.getMilliseconds() on start and on end, and i will add the result of **end - start** all the time to each others and save it in a long value, am I right ? – MBH Mar 31 '16 at 20:23
  • 1
    Glad to be of help. Cheers! :) – Swayam Mar 31 '16 at 20:26
0

You can keep track of all the milliseconds using Date().getTime(), which returns the time since Epoch. So whenever you need to add/remove, just take your Date object, invoke .getTime(), and add/remove from the total. Then when you're done, you can convert the milliseconds to whatever format you need.

The Hungry Androider
  • 2,274
  • 5
  • 27
  • 52