• Post Reply Bookmark Topic Watch Topic
  • New Topic

Any way round creating a new Date() each time?

 
Frank Carver
Sheriff
Posts: 6920
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
In a current application I need to get the current date/time as a long in many different places. At the moment I use something like
long now = new Date().getTime();
each time I need to get the current date/time, but this repeated creation of "throwaway" Date objects worries me as it goes against everything which has been discussed here.
Does anyone know of a way of getting the current date/time as a long without creating any objects - a static method somewhere?
 
Peter Tran
Bartender
Posts: 783
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Frank,
Not that I can see. We had the same problem in an application I worked on, and we resorted to using a Singleton to keep one instance of the Date() object around. Of course this force all other part of the program to share the same Date value which was acceptable for our requirements. It may not work for you.
If you find a solution, I would be very interested in hearing it.
-Peter
 
Susan Hoover
Ranch Hand
Posts: 64
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Try System.currentTimeMillis() -- it's a static method.
<pre>
public static long currentTimeMillis()
Returns the current time in milliseconds.
</pre>
 
Peter Tran
Bartender
Posts: 783
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Susan,
Looking at the source file for System.java, the signature for currentTimeMillis() is:
public static native long currentTimeMillis();
Wouldn't a native call be potentially slower?
-Peter
 
Susan Hoover
Ranch Hand
Posts: 64
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Ah, but if you look at the code for the default java.util.Date constructor...

 
Peter Tran
Bartender
Posts: 783
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Touche!
And he's down for the count...Ladies and Gentleman, I don't think Peter's getting up from this last round. It's over! It's a full count. Susan takes it home in the 2nd round...

[This message has been edited by Peter Tran (edited January 24, 2001).]
 
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!