0

In my Java application, I use several libraries which invoke System.currentTimeMillis() and Instant.now(). These functions provide the current timestamp.
I would like to set the time of the application to something different than the real time.
E.g. 1 Jan 2023 16:00.

This will be set once at the start. During the course of execution, I want all current timestamp invocations to believe that the application has started at that time and will show timestamps accordingly, regardless of the real system time. I would like to do this without changing the time of the computer and without affectiing other applications running on the computer.
Is this possible?

deHaar
  • 17,687
  • 10
  • 38
  • 51
Yash
  • 946
  • 1
  • 13
  • 28
  • You can create a custom `OffsetDateTime` or `ZonedDateTime` and get the corresponding `Instant` from it without having to rely on the current date or time. – deHaar Mar 22 '23 at 13:51

2 Answers2

0

If you want to create your own timestamp and get its epoch milli values, you could create an OffsetDateTime (or ZonedDateTime) from your desired value, convert it to an Instant and receive the moment in time represented by epoch millis:

public static void main(String[] args) {
    // create a custom date and time in UTC
    OffsetDateTime customOdt = OffsetDateTime.of(
                2023, 1, 1, 16, 0, 0, 0, ZoneOffset.UTC
            );
    // print it
    System.out.println(customOdt);
    // then print the underlying Instant
    System.out.println(customOdt.toInstant().toEpochMilli());
}

Output:

2023-01-01T16:00Z
1672588800000
deHaar
  • 17,687
  • 10
  • 38
  • 51
  • This would mean all the libraries and third part code that I am using will have to be modified to use the OffsetDateTime. I am trying to avoid that. – Yash Mar 22 '23 at 14:24
  • Then maybe manipulate `Instant.now()` with a `Clock`, follow the link under your question… – deHaar Mar 22 '23 at 15:11
0

The best practice would be to use a Clock to provide the current instant. A dependency injection framework would be the best way to achieve this. This allows you to pass in either a system clock, a clock in an alternate time zone, a clock with an offset or a clock that always returns a fixed time.

function doSomethingWithTime(LocalDateTime time, Clock clock) {
    assert time.isBefore(LocalDateTime.now(clock));
}
David Jones
  • 2,879
  • 2
  • 18
  • 23