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?
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.
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.
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.
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.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With