Reputation: 822
I have a java app using date() to obtain the current date, and I'm trying to manipulate the date that it is obtaining from date() for testing purposes.
I've tried setting the system date(on Windows) to a date in the past for example 1/1/2014, but the java app seems to keep getting the realtime date from somewhere other than the system date.
Is it possible to manipulate the date and if so, how can I manipulate the date that the date() function returns from outside the binary?
Upvotes: 2
Views: 263
Reputation: 19905
The Date
class in Java
uses the system time reported via System.currentTimeMillis(). This, in Windows
, invokes the low resolution Win32/64
API call GetSystemTimeAsFileTime()
, which always returns "the current system date and time in UTC format", as per Microsoft documentation.
If there was access to the code and the requirement were to produce a custom Date
object, representing some arbitrary time besides current, the recommended way would have been via the Calendar
class.
For example:
Calendar calendar = new GregorianCalendar();
calendar.set(Calendar.YEAR, 2014);
calendar.set(Calendar.MONTH, 0); // 0 = January, 11 = December
calendar.set(Calendar.DAY_OF_MONTH, 1); // 1 to 31
Given the above, a new Date
object can be retrieved as follows:
Date date = calendar.getTime();
Upvotes: 1
Reputation: 339412
No need to manipulate from outside Java. Your tests within Java can alter the values reported as the current moment.
You are using old outmoded classes. Those classes have been supplanted by the java.time framework built into Java 8 and later.
You can override the abstract Clock
class to supply your own implementation. Your class can alter the date-time it reports as needed for your testing purposes.
The Clock
class offers some static methods such as fixed
, offset
, and tick
to conveniently provide altered Implementations.
Upvotes: 2