JodaTime setCurrentMillisSystem()

  • Post author:
  • Post category:Java

When programs have logic based on the current time, it’s important to be able to programmatically set the current time for testing purposes. Other not so great options we have to change the computer clock, or change the logic for testing, or change the date in the database. Using JodaTime, it’s easy to programatically change the system time. Here are the things you need to do.

1. Make sure you use JodaTime’s DateTime class instead of java.util.Date when working with dates. Only convert DateTime to java.util.Date or java.sql.Date during persistence or when you are done with all date calculations and logic.

2. Call JodaTime’s DateTimeUtils.setCurrentMillisFixed(int millis) to set the system time. Here’s an example of setting the system time to 2013-09-23 10:30 AM.

DateTimeUtils.setCurrentMillisFixed(new DateTime(2013, 9, 23, 10, 30).getMillis());
DateTime now = new DateTime();
System.out.println(now);

This code prints

2013-09-23T10:30:00.000-04:00

3. To undo setCurrentMillisFixed, call DateTimeUtils.setCurrentMillisSystem(). This should return the real system time again.

DateTimeUtils.setCurrentMillisSystem();

In your related JUnit tests, you can put setCurrentMillisSystem() in the @After function

@After
public void after() {
DateTimeUtils.setCurrentMillisSystem();
}