Java date difference in milliseconds

Every time I need to do math on a date in java, I end up googling it. While that isn’t the worst way to do things (hey, it’s probably how you found this :)), I wanted something I *knew* would be there. I know there are libraries out there for this, but I usually want something very simple like, “run this in a loop for 60 seconds”. Here is what I use…

long START_TIME = new java.util.Date().getTime();
while (new java.util.Date().getTime() - START_TIME < 60000) {
  //do something
}

I don't know how efficient the getTime() method is, but this works. You could also use System.currentTimeMillis()...

long START_TIME = new java.util.Date().getTime();
while (System.currentTimeMillis() - START_TIME < 60000) {
  //do something
}

My guess is this is more efficient. One of these days I will test it.

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.