Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Mocking time in Java 8's java.time API

Joda Time has a nice DateTimeUtils.setCurrentMillisFixed() to mock time.

It's very practical in tests.

Is there an equivalent in Java 8's java.time API?

like image 842
neu242 Avatar asked Jun 30 '14 13:06

neu242


People also ask

What is a Zonedtime in the Java 8 date and time API?

time introduced a new date-time API, most important classes among them are : Local : Simplified date-time API with no complexity of timezone handling. Zoned : Specialized date-time API to deal with various timezones.

How do you mock a timestamp in Java?

SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); sdf. setTimeZone(TimeZone. getTimeZone("PST")); Date NOW = sdf. parse("2019-02-11 00:00:00"); Timestamp time=new Timestamp(NOW.

How will you get current date and time using Java 8 date and time API?

An instance of current date can be created from the system clock: LocalDate localDate = LocalDate. now(); And we can get the LocalDate representing a specific day, month and year by using the of method or the parse method.

How do I get the current time in Java 8?

You can get the time from the LocaldateTime object using the toLocalTime() method. Therefore, another way to get the current time is to retrieve the current LocaldateTime object using the of() method of the same class. From this object get the time using the toLocalTime() method.


1 Answers

The closest thing is the Clock object. You can create a Clock object using any time you want (or from the System current time). All date.time objects have overloaded now methods that take a clock object instead for the current time. So you can use dependency injection to inject a Clock with a specific time:

public class MyBean {     private Clock clock;  // dependency inject     ...     public void process(LocalDate eventDate) {       if (eventDate.isBefore(LocalDate.now(clock)) {         ...       }     }   } 

See Clock JavaDoc for more details

like image 181
dkatzel Avatar answered Sep 23 '22 13:09

dkatzel