A generator of random dates. @author pmiklos
| 15 | * |
| 16 | */ |
| 17 | public class DateAndTime { |
| 18 | private static final int DEFAULT_MIN_AGE = 18; |
| 19 | private static final int DEFAULT_MAX_AGE = 65; |
| 20 | |
| 21 | private final Faker faker; |
| 22 | |
| 23 | protected DateAndTime(Faker faker) { |
| 24 | this.faker = faker; |
| 25 | } |
| 26 | |
| 27 | /** |
| 28 | * Generates a future date from now. Note that there is a 1 second slack to avoid generating a past date. |
| 29 | * |
| 30 | * @param atMost |
| 31 | * at most this amount of time ahead from now exclusive. |
| 32 | * @param unit |
| 33 | * the time unit. |
| 34 | * @return a future date from now. |
| 35 | */ |
| 36 | public Date future(int atMost, TimeUnit unit) { |
| 37 | Date now = new Date(); |
| 38 | Date aBitLaterThanNow = new Date(now.getTime() + 1000); |
| 39 | return future(atMost, unit, aBitLaterThanNow); |
| 40 | } |
| 41 | |
| 42 | /** |
| 43 | * Generates a future date from now, with a minimum time. |
| 44 | * |
| 45 | * @param atMost |
| 46 | * at most this amount of time ahead from now exclusive. |
| 47 | * @param minimum |
| 48 | * the minimum amount of time in the future from now. |
| 49 | * @param unit |
| 50 | * the time unit. |
| 51 | * @return a future date from now. |
| 52 | */ |
| 53 | public Date future(int atMost, int minimum, TimeUnit unit) { |
| 54 | Date now = new Date(); |
| 55 | Date minimumDate = new Date(now.getTime() + unit.toMillis(minimum)); |
| 56 | return future(atMost - minimum, unit, minimumDate); |
| 57 | } |
| 58 | |
| 59 | /** |
| 60 | * Generates a future date relative to the {@code referenceDate}. |
| 61 | * |
| 62 | * @param atMost |
| 63 | * at most this amount of time ahead to the {@code referenceDate} exclusive. |
| 64 | * @param unit |
| 65 | * the time unit. |
| 66 | * @param referenceDate |
| 67 | * the future date relative to this date. |
| 68 | * @return a future date relative to {@code referenceDate}. |
| 69 | */ |
| 70 | public Date future(int atMost, TimeUnit unit, Date referenceDate) { |
| 71 | long upperBound = unit.toMillis(atMost); |
| 72 | |
| 73 | long futureMillis = referenceDate.getTime(); |
| 74 | futureMillis += 1 + faker.random().nextLong(upperBound - 1); |
nothing calls this directly
no outgoing calls
no test coverage detected