File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
The moose likes Beginning Java and the fly likes system time/clock Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Java » Beginning Java
Bookmark "system time/clock" Watch "system time/clock" New topic

system time/clock

Ed Zeval

Joined: Jun 19, 2008
Posts: 21

Is there a way to change the system clock? I just want to be able to change it for some tests. How would you change it back to the correct time?

Ulf Dittmer

Joined: Mar 22, 2005
Posts: 42965
You mean programmatically in Java? I don't think there is, unless you want to use JNI to access system routines.

Manually changing the clock is not sufficient for your purposes?
Ed Zeval

Joined: Jun 19, 2008
Posts: 21
Yeah.. i mean programmatically..

Manually wouldn't work since I want to automate these tests..

If I can't actually change the clock, is there a way to fake/mock it?
Henry Wong

Joined: Sep 28, 2004
Posts: 20531

I am assuming that these tests are started with shellscripts? If so, you can add a call to the "date" command, prior to the call to start the JVM, to set the date. To set it back, you can use the "rdate" command to a host with a time server.


Books: Java Threads, 3rd Edition, Jini in a Nutshell, and Java Gems (contributor)
Ernest Friedman-Hill
author and iconoclast

Joined: Jul 08, 2003
Posts: 24199

As with most things in computing, this is probably easy to solve with another layer of indirection.

Everywhere in your code that you now say, e.g., "new Date()" or System.currentTimeMillis(), or however you determine what time it is, replace those with something like "TimeFactory.get().newDate()" or "TimeFactory.get().currentTimeMillis()". TimeFactory.get() returns an object that has methods like newDate(), currentTimeMillis(), or whatever else you need, declared in an interface "ITime" or something.

get() looks like (This leaves out exception handling and also ignores that the System property might be null; you need to deal with those issues

Now, you can change the ITime object -- and therefore how the whole app tells time -- with a system property. You can implement one that reports a fixed time, or a delayed time, or an accelerated time, or whatever you need.

[Jess in Action][AskingGoodQuestions]
Marilyn de Queiroz

Joined: Jul 22, 2000
Posts: 9059
I think setDefaultTimezone() resets the timezone of the JVM that's currently running ... but that won't help if you want a different month or something like that.

"Yesterday is history, tomorrow is a mystery, and today is a gift; that's why they call it the present." Eleanor Roosevelt
I agree. Here's the link:
subject: system time/clock
jQuery in Action, 3rd edition