Archit Sharma
Archit Sharma

Reputation: 15

Maintaining a separate application time in Java?

I am running a web application from eclipse. On this web application I want to set the current date and time to 24/11/1992. 00:00 hrs GMT. After this I want the application to auto increment the time and keep a track of the date,month and year. Is there any way i can do this in Java/JSP?

Upvotes: 1

Views: 94

Answers (1)

Bruno Reis
Bruno Reis

Reputation: 37832

You should store the difference between the "real current time" and the "past current time", and do a subtraction each time you want to check the past time:

final class Past {
  private final long differenceMs;
  public Past(final Date pastDate) {
    this.differenceMs = (System.currentTimeMillis() - pastDate.getTime());
  }
  public Date getUpdatedPastDate() {
    return new Date(System.currentTimeMillis() - differenceMs);
  }
}

class Test {
  public static void main(String[] args) throws Throwable {
    final Calendar cal = Calendar.getInstance();
    cal.set(1992, 10, 24, 0, 0, 0); // this is 24/11/1992
    final Past past = new Past(cal.getTime());
    System.out.println(past.getUpdatedPastDate());
    Thread.sleep(2000);
    System.out.println(past.getUpdatedPastDate());
  }
}

The two println shall print something like Tue Nov 24 00:00:00 BRST 1992 and Tue Nov 24 00:00:02 BRST 1992 (depending on your locale).

There's no need to "auto increment", there's no multithreading, the class is immutable (hence inherently thread-safe) and very, very clean.

Upvotes: 3

Related Questions