In Joda we have setCurrentMillisFixed method which can be used to set future date
In one my test cases , i pass a DateTime (joda) parameter to
current system time:
DateTime created = new DateTime()
DateTimeUtils.setCurrentMillisSystem(created.toInstant().toEpochMilli()););
In Java 8 i am trying : I pass ZonedDateTime instead of DateTime,
I tried setting the date as below:
ZonedDateTime.now(Clock.fixed(Instant.now().plusMillis(created.toInstant().toEpochMilli()),ZoneId.systemDefault()));
But lot of test cases are failing, i am guessing this has something to do with how the date is being set.
Any advice ? Could not find any useful piece of code ,
Year 2066?
I suspect you are setting an unintended moment, around 50 years in the future.
Let’s unpack your code.
So you start with about 5 decades of nanoseconds. Then, presumably, you add approximately another 5 decades of milliseconds. So you end up with a date fifty years in the future, around the year 2066. Is that the value you intended to test?
We can try that code, so see the result.
Sure enough, year 2066, if
created
is a moment earlier this year.Millis vs nanos
Be aware that the java.time classes such as
Instant
andZonedDateTime
have a resolution of nanoseconds. That is much finer than the old legacy classesjava.util.Date
&Calendar
which use milliseconds.Write simple code
Tip: Don't write so much into one line of code. Hard for humans to decipher and to debug/trace. And may be harder for the JVM to optimize. Writing dead-simple lines of code is easier on both humans and machines, generally.
So, let’s break up that code into simple lines.
Now pass that
Clock
object namedclock
to your code being tested.Try it.
Yes, it worked. We see the minute-of-hour as
27
rather than22
, five minutes in the future.Pass a
Clock
in production.To run that same code in production, outside your test harness, pass the default
Clock
implementation.About java.time
The java.time framework is built into Java 8 and later. These classes supplant the troublesome old legacy date-time classes such as
java.util.Date
,Calendar
, &SimpleDateFormat
.The Joda-Time project, now in maintenance mode, advises migration to the java.time classes.
To learn more, see the Oracle Tutorial. And search Stack Overflow for many examples and explanations. Specification is JSR 310.
You may exchange java.time objects directly with your database. Use a JDBC driver compliant with JDBC 4.2 or later. No need for strings, no need for
java.sql.*
classes.Where to obtain the java.time classes?
The ThreeTen-Extra project extends java.time with additional classes. This project is a proving ground for possible future additions to java.time. You may find some useful classes here such as
Interval
,YearWeek
,YearQuarter
, and more.