Java Code Examples for java.time.ZonedDateTime#now()

The following examples show how to use java.time.ZonedDateTime#now() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: ExecutionTimeCron4jIntegrationTest.java    From cron-utils with Apache License 2.0 6 votes vote down vote up
/**
 * Issue #37: nextExecution not calculating correct time.
 */
@Test
public void testEvery2Hours() {
    ZonedDateTime lastRun = ZonedDateTime.now();
    final ExecutionTime executionTime = ExecutionTime.forCron(cron4jCronParser.parse(EVERY_2_HOURS));

    // iterate through the next 36 hours so we roll over the to the next day
    // and make sure the next run time is always in the future from the prior run time
    for (int i = 0; i < 36; i++) {

        final Optional<ZonedDateTime> nextExecution = executionTime.nextExecution(lastRun);
        if (nextExecution.isPresent()) {
            final ZonedDateTime nextRun = nextExecution.get();
            log.info(LOG_LAST_RUN, lastRun);
            log.info(LOG_NEXT_RUN, nextRun);

            assertTrue(String.format("Hour is %s", nextRun.getHour()), nextRun.getHour() % 2 == 0);
            assertTrue(String.format("Last run is before next one: %s", lastRun.isBefore(nextRun)), lastRun.isBefore(nextRun));
            lastRun = lastRun.plusHours(1);
        } else {
            fail(NEXT_EXECUTION_NOT_PRESENT_ERROR);
        }
    }
}
 
Example 2
Source File: AbstractDomainEventSpecs.java    From loom with MIT License 6 votes vote down vote up
@Test
public void constructor_has_guard_clause_for_null_aggregateId() {
    // Arrange
    UUID aggregateId = null;

    // Act
    IllegalArgumentException expected = null;
    try {
        new IssueCreatedForTesting(aggregateId, 1, ZonedDateTime.now());
    } catch (IllegalArgumentException e) {
        expected = e;
    }

    // Assert
    Assert.assertNotNull(expected);
    Assert.assertTrue(
            "The error message should contain the name of the parameter 'aggregateId'.",
            expected.getMessage().contains("'aggregateId'"));
}
 
Example 3
Source File: SettableDataSetterFactoryTest.java    From SimpleFlatMapper with MIT License 5 votes vote down vote up
@Test
public void testJava8TimeZDT() throws Exception {
    Setter<SettableByIndexData, ZonedDateTime> setter = factory.getSetter(newPM(ZonedDateTime.class, DataType.timestamp()));

    ZonedDateTime ldt = ZonedDateTime.now();

    setter.set(statement, ldt);
    setter.set(statement, null);

    verify(statement).setTimestamp(0, Date.from(ldt.toInstant()));
    verify(statement).setToNull(0);
}
 
Example 4
Source File: TemporalRoundingTest.java    From phoebus with Eclipse Public License 1.0 5 votes vote down vote up
@Test
public void testRandomRounding()
{
    final DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss (z, 'UTC' Z)");
    final ZonedDateTime start = ZonedDateTime.now();
    for (ChronoUnit unit : SUPPORTED_UNITS)
    {
        final int amount = (int)(Math.random()*60);
        final ZonedDateTime rd = start.with(zonedDateTimerRoundedToNextOrSame(unit, amount));
        System.out.println(formatter.format(start) + " rounded by " + amount + " " + unit + " -> " +
                           formatter.format(rd));
    }
}
 
Example 5
Source File: BootNotificationConfirmationTest.java    From Java-OCA-OCPP with MIT License 5 votes vote down vote up
@Test
public void setCurrentTime_now_currentTimeIsSet() {
  // Given
  ZonedDateTime now = ZonedDateTime.now();

  // When
  confirmation.setCurrentTime(now);

  // Then
  assertThat(confirmation.getCurrentTime(), equalTo(now));
}
 
Example 6
Source File: TestPullRequest.java    From skara with GNU General Public License v2.0 5 votes vote down vote up
@Override
public void updateCheck(Check updated) {
    var existing = data.checks.stream()
            .filter(check -> check.name().equals(updated.name()))
            .findAny()
            .orElseThrow();

    data.checks.remove(existing);
    data.checks.add(updated);
    data.lastUpdate = ZonedDateTime.now();
}
 
Example 7
Source File: TCKZonedDateTime.java    From openjdk-8 with GNU General Public License v2.0 5 votes vote down vote up
@Test
public void now_ZoneId() {
    ZoneId zone = ZoneId.of("UTC+01:02:03");
    ZonedDateTime expected = ZonedDateTime.now(Clock.system(zone));
    ZonedDateTime test = ZonedDateTime.now(zone);
    for (int i = 0; i < 100; i++) {
        if (expected.equals(test)) {
            return;
        }
        expected = ZonedDateTime.now(Clock.system(zone));
        test = ZonedDateTime.now(zone);
    }
    assertEquals(test, expected);
}
 
Example 8
Source File: HotTest.java    From expper with GNU General Public License v3.0 5 votes vote down vote up
public static void initialize(long size) {
    for (long i = 0; i < size; ++i) {
        PostMeta post = new PostMeta();
        post.id = i;
        post.ups = (int) (Math.random() * 10000);
        post.downs = (int) (Math.random() * 10000);
        ZonedDateTime date = ZonedDateTime.now();
        date = date.minusHours((int) (Math.random() * 24 * 30 * 6));
        date = date.minusSeconds((int) (Math.random() * 3600));
        post.createdAt = date;
        post.hot = (int) (Math.random() * 2000);

        posts.add(post);
    }
}
 
Example 9
Source File: RepositoryChunk.java    From dragonwell8_jdk with GNU General Public License v2.0 5 votes vote down vote up
RepositoryChunk(SafePath path, Instant startTime) throws Exception {
    ZonedDateTime z = ZonedDateTime.now();
    String fileName = Repository.REPO_DATE_FORMAT.format(
            LocalDateTime.ofInstant(startTime, z.getZone()));
    this.startTime = startTime;
    this.repositoryPath = path;
    this.unFinishedFile = findFileName(repositoryPath, fileName, ".part");
    this.file = findFileName(repositoryPath, fileName, ".jfr");
    this.unFinishedRAF = SecuritySupport.createRandomAccessFile(unFinishedFile);
    SecuritySupport.touch(file);
}
 
Example 10
Source File: Notification.java    From notification with Apache License 2.0 5 votes vote down vote up
/**
 * Constructor
 *
 * @param category
 * @param message
 */
@JsonCreator
private Notification(
    @JsonProperty("category") final String category,
    @JsonProperty("message") final String message) {
  this.id = Optional.empty();
  this.category = category;
  this.message = message;
  this.createdAt = ZonedDateTime.now(Clock.systemUTC());
  this.unseen = Optional.empty();
  this.properties = Collections.emptyMap();
  this.notifications = Collections.emptyList();
}
 
Example 11
Source File: TCKZonedDateTime.java    From openjdk-8 with GNU General Public License v2.0 5 votes vote down vote up
@Test
public void now_Clock_offsets() {
    ZonedDateTime base = ZonedDateTime.of(LocalDateTime.of(1970, 1, 1, 12, 0), ZoneOffset.UTC);
    for (int i = -9; i < 15; i++) {
        ZoneOffset offset = ZoneOffset.ofHours(i);
        Clock clock = Clock.fixed(base.toInstant(), offset);
        ZonedDateTime test = ZonedDateTime.now(clock);
        assertEquals(test.getHour(), (12 + i) % 24);
        assertEquals(test.getMinute(), 0);
        assertEquals(test.getSecond(), 0);
        assertEquals(test.getNano(), 0);
        assertEquals(test.getOffset(), offset);
        assertEquals(test.getZone(), offset);
    }
}
 
Example 12
Source File: ExecutionTimeQuartzIntegrationTest.java    From cron-utils with Apache License 2.0 5 votes vote down vote up
/**
 * Issue #30: execution time properly calculated.
 */
@Test
public void testSaturdayExecutionTime() {
    final ZonedDateTime now = ZonedDateTime.now();
    final ExecutionTime executionTime = ExecutionTime.forCron(parser.parse("0 0 3 ? * 6"));
    final Optional<ZonedDateTime> lastExecution = executionTime.lastExecution(now);
    final Optional<ZonedDateTime> nextExecution = executionTime.nextExecution(now);
    if (lastExecution.isPresent() && nextExecution.isPresent()) {
        final ZonedDateTime last = lastExecution.get();
        final ZonedDateTime next = nextExecution.get();
        assertNotEquals(last, next);
    } else {
        fail(ASSERTED_EXECUTION_NOT_PRESENT);
    }
}
 
Example 13
Source File: ReviewersCheckTests.java    From skara with GNU General Public License v2.0 5 votes vote down vote up
private static Commit commit(Author author, List<String> reviewers) {
    var hash = new Hash("0123456789012345678901234567890123456789");
    var parents = List.of(new Hash("12345789012345789012345678901234567890"));
    var authored = ZonedDateTime.now();
    var message = new ArrayList<String>();
    message.addAll(List.of("Initial commit"));
    if (!reviewers.isEmpty()) {
        message.addAll(List.of("", "Reviewed-by: " + String.join(", ", reviewers)));
    }
    var metadata = new CommitMetadata(hash, parents, author, authored, author, authored, message);
    return new Commit(metadata, List.of());
}
 
Example 14
Source File: TCKZonedDateTime.java    From openjdk-jdk8u-backup with GNU General Public License v2.0 5 votes vote down vote up
@Test
public void now() {
    ZonedDateTime expected = ZonedDateTime.now(Clock.systemDefaultZone());
    ZonedDateTime test = ZonedDateTime.now();
    long diff = Math.abs(test.toLocalTime().toNanoOfDay() - expected.toLocalTime().toNanoOfDay());
    if (diff >= 100000000) {
        // may be date change
        expected = ZonedDateTime.now(Clock.systemDefaultZone());
        test = ZonedDateTime.now();
        diff = Math.abs(test.toLocalTime().toNanoOfDay() - expected.toLocalTime().toNanoOfDay());
    }
    assertTrue(diff < 100000000);  // less than 0.1 secs
}
 
Example 15
Source File: InsightsUtils.java    From Insights with Apache License 2.0 4 votes vote down vote up
public static ZonedDateTime getTodayTimeX() {
	ZonedDateTime now = ZonedDateTime.now(zoneId);
	return now;
}
 
Example 16
Source File: TopicPartitionRecordGrouperTest.java    From aiven-kafka-connect-gcs with GNU Affero General Public License v3.0 4 votes vote down vote up
@Test
void rotateKeysHourly() {
    final Template filenameTemplate =
        Template.of(
            "{{topic}}-"
                + "{{partition}}-"
                + "{{start_offset}}-"
                + "{{timestamp:unit=YYYY}}"
                + "{{timestamp:unit=MM}}"
                + "{{timestamp:unit=dd}}"
                + "{{timestamp:unit=HH}}"
        );
    final TimestampSource timestampSourceMock = mock(TimestampSource.class);

    final ZonedDateTime firstHourTime = ZonedDateTime.now();
    final ZonedDateTime secondHourTime = firstHourTime.plusHours(1);
    final String firstHourTs =
        firstHourTime.format(DateTimeFormatter.ofPattern("YYYY"))
            + firstHourTime.format(DateTimeFormatter.ofPattern("MM"))
            + firstHourTime.format(DateTimeFormatter.ofPattern("dd"))
            + firstHourTime.format(DateTimeFormatter.ofPattern("HH"));
    final String secondHourTs =
        secondHourTime.format(DateTimeFormatter.ofPattern("YYYY"))
            + secondHourTime.format(DateTimeFormatter.ofPattern("MM"))
            + secondHourTime.format(DateTimeFormatter.ofPattern("dd"))
            + secondHourTime.format(DateTimeFormatter.ofPattern("HH"));

    when(timestampSourceMock.time()).thenReturn(firstHourTime);
    final TopicPartitionRecordGrouper grouper =
        new TopicPartitionRecordGrouper(
            filenameTemplate,
            null,
            timestampSourceMock
        );

    grouper.put(T0P0R1);
    grouper.put(T0P0R2);
    grouper.put(T0P0R3);

    when(timestampSourceMock.time()).thenReturn(secondHourTime);

    grouper.put(T0P0R4);
    grouper.put(T0P0R5);

    final Map<String, List<SinkRecord>> records = grouper.records();

    assertEquals(2, records.size());

    assertThat(
        records.keySet(),
        containsInAnyOrder(
            "topic0-0-1-" + firstHourTs,
            "topic0-0-1-" + secondHourTs
        )
    );
    assertThat(
        records.get("topic0-0-1-" + firstHourTs),
        contains(T0P0R1, T0P0R2, T0P0R3)
    );
    assertThat(
        records.get("topic0-0-1-" + secondHourTs),
        contains(T0P0R4, T0P0R5)
    );
}
 
Example 17
Source File: MinionActionManagerTest.java    From uyuni with GNU General Public License v2.0 4 votes vote down vote up
/**
 * Test that no staging jobs are scheduled when config parameters
 * are scheduled to design a staging window in which start equals
 * end
 *
 * @throws Exception when Taskomatic service is down
 */
public void testNoStagingJobsWhenWindowStartEqualsFinish() throws Exception {
    user.addPermanentRole(RoleFactory.ORG_ADMIN);

    UserFactory.save(user);
    MinionServer minion1 = MinionServerFactoryTest.createTestMinionServer(user);
    minion1.setOrg(user.getOrg());
    MinionServer minion2 = MinionServerFactoryTest.createTestMinionServer(user);
    minion2.setOrg(user.getOrg());

    user.getOrg().getOrgConfig().setStagingContentEnabled(true);
    Config.get().setString(SALT_CONTENT_STAGING_WINDOW, "0");
    Config.get().setString(SALT_CONTENT_STAGING_ADVANCE, "0");

    final ZonedDateTime now = ZonedDateTime.now(ZoneId.systemDefault());
    final ZonedDateTime executionTime = now.plusHours(24);

    Action action = ActionManager.createAction(user, ActionFactory.TYPE_PACKAGES_UPDATE,
            "test action", Date.from(now.toInstant()));
    ActionManager.scheduleForExecution(action,
            new HashSet<Long>(Arrays.asList(minion1.getId(), minion2.getId())));
    ActionFactory.save(action);

    TaskomaticApi taskomaticMock = mock(TaskomaticApi.class);
    MinionActionManager.setTaskomaticApi(taskomaticMock);

    context().checking(new Expectations() { {
        never(taskomaticMock).scheduleStagingJob(with(action.getId()),
                with(minion1.getId()),
                with(any(Date.class)));
        never(taskomaticMock).scheduleStagingJob(with(action.getId()),
                with(minion2.getId()),
                with(any(Date.class)));
    } });

    Map<Long, Map<Long, ZonedDateTime>> actionsDataMap =
            MinionActionManager.scheduleStagingJobsForMinions(Collections.singletonList(action), user);
    List<ZonedDateTime> scheduleTimes =
            actionsDataMap.values().stream().map(s -> new ArrayList<>(s.values()))
                    .flatMap(List::stream).collect(Collectors.toList());

    assertEquals(0,
            scheduleTimes.stream()
                .filter(scheduleTime -> scheduleTime.isAfter(now))
                .filter(scheduleTime -> scheduleTime.isBefore(executionTime))
                .collect(Collectors.toList()).size());
}
 
Example 18
Source File: OrderManager.java    From problematic-microservices with BSD 3-Clause "New" or "Revised" License 4 votes vote down vote up
public RobotOrder createNewOrder(long customerId, RobotOrderLineItem[] lineItems) {
	return new RobotOrder(SERIAL_ID_GENERATOR.getAndIncrement(), customerId, ZonedDateTime.now(), lineItems);
}
 
Example 19
Source File: EarthClock.java    From mars-sim with GNU General Public License v3.0 4 votes vote down vote up
/**
 * Constructor.
 * 
 * @param fullDateTimeString the UT date string
 * @throws Exception if date string is invalid.
 */
public EarthClock(String fullDateTimeString) {
	// Java 8's Date/Time API in java.time package, see
	// https://docs.oracle.com/javase/tutorial/datetime/TOC.html
	
	// dtFormatter_millis = DateTimeFormatter.ofPattern("yyyy-MMM-dd HH:mm:ss");//.AAAA");//AAAA");

	// see http://stackoverflow.com/questions/26142864/how-to-get-utc0-date-in-java-8

	// Use ZonedDate
	zonedDateTime = ZonedDateTime.now(ZoneOffset.UTC);
	
	// Set Greenwich Mean Time (GMT) timezone for calendar
	zone = new SimpleTimeZone(0, "GMT");
	// see http://www.diffen.com/difference/GMT_vs_UTC

	// Set Earth clock to Martian Zero-orbit date-time.
	// This date may need to be adjusted if it is inaccurate.

	// Set it to Locale.US
	f0 = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss '(UT)'", Locale.US);
	f0.setTimeZone(zone);

	// Set it to Locale.US
	f1 = new SimpleDateFormat("yyyy-MM-dd HH:mm '(UT)'", Locale.US);
	f1.setTimeZone(zone);

	// Note: By default, java set locale to user's machine system locale via
	// Locale.getDefault(Locale.Category.FORMAT));
	// i.e. f2 = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss",
	// Locale.getDefault(Locale.Category.FORMAT));
	// 2017-03-27 set it to Locale.US

	f2 = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.SSS", Locale.US);
	f2.setTimeZone(zone);

	String iso8601 = null;

	// The default value for fullDateTimeString from simulations.xml is "2028-08-17 15:23:13.740"
	iso8601 = fullDateTimeString.replace(" ", "T") + "Z";

	dateOfFirstLanding = ZonedDateTime.parse(iso8601);
	// LocalDateTime ldt = zdt.toLocalDateTime();

	try {
		zonedDateTime = dateOfFirstLanding;
		computeMillisAtStart();
	} catch (Exception ex) {
		ex.printStackTrace();
	}

	// Initialize a second formatter
	// Set it to Locale.US
	f3 = new SimpleDateFormat("yyyy-MM-dd HH:mm", Locale.US);// .SSS"); // :SSS
	TimeZone gmt = TimeZone.getTimeZone("GMT");
	f3.setTimeZone(gmt);
	f3.setLenient(false);

}
 
Example 20
Source File: ZonedDateTimeUnitTest.java    From tutorials with MIT License 4 votes vote down vote up
@Test
public void givenZonedDateTime_whenConvertToString_thenOk() {

    ZonedDateTime zonedDateTimeNow = ZonedDateTime.now(ZoneId.of("UTC"));
    ZonedDateTime zonedDateTimeOf = ZonedDateTime.of(2018, 01, 01, 0, 0, 0, 0, ZoneId.of("UTC"));

    LocalDateTime localDateTime = LocalDateTime.now();
    ZonedDateTime zonedDateTime = ZonedDateTime.of(localDateTime, ZoneId.of("UTC"));

    DateTimeFormatter formatter = DateTimeFormatter.ofPattern("MM/dd/yyyy - HH:mm:ss Z");
    String formattedString = zonedDateTime.format(formatter);

    DateTimeFormatter formatter2 = DateTimeFormatter.ofPattern("MM/dd/yyyy - HH:mm:ss z");
    String formattedString2 = zonedDateTime.format(formatter2);

    log.info(formattedString);
    log.info(formattedString2);

}