Exemplo n.º 1
0
  public static void main(String[] args) {

    // Current Date
    LocalDateTime today = LocalDateTime.now();
    System.out.println("Current DateTime=" + today);

    // Current Date using LocalDate and LocalTime
    today = LocalDateTime.of(LocalDate.now(), LocalTime.now());
    System.out.println("Current DateTime=" + today);

    // Creating LocalDateTime by providing input arguments
    LocalDateTime specificDate = LocalDateTime.of(2014, Month.JANUARY, 1, 10, 10, 30);
    System.out.println("Specific Date=" + specificDate);

    // Try creating date by providing invalid inputs
    // LocalDateTime feb29_2014 = LocalDateTime.of(2014, Month.FEBRUARY, 28,
    // 25,1,1);
    // Exception in thread "main" java.time.DateTimeException:
    // Invalid value for HourOfDay (valid values 0 - 23): 25

    // Current date in "Asia/Kolkata", you can get it from ZoneId javadoc
    LocalDateTime todayKolkata = LocalDateTime.now(ZoneId.of("Asia/Kolkata"));
    System.out.println("Current Date in IST=" + todayKolkata);

    // java.time.zone.ZoneRulesException: Unknown time-zone ID: IST
    // LocalDateTime todayIST = LocalDateTime.now(ZoneId.of("IST"));

    // Getting date from the base date i.e 01/01/1970
    LocalDateTime dateFromBase = LocalDateTime.ofEpochSecond(10000, 0, ZoneOffset.UTC);
    System.out.println("10000th second time from 01/01/1970= " + dateFromBase);
  }
Exemplo n.º 2
0
 // -----------------------------------------------------------------------
 // isSupportedBy(TemporalAccessor temporal) and getFrom(TemporalAccessor temporal)
 // -----------------------------------------------------------------------
 @DataProvider(name = "fieldAndAccessor")
 Object[][] data_fieldAndAccessor() {
   return new Object[][] {
     {YEAR, LocalDate.of(2000, 2, 29), true, 2000},
     {YEAR, LocalDateTime.of(2000, 2, 29, 5, 4, 3, 200), true, 2000},
     {MONTH_OF_YEAR, LocalDate.of(2000, 2, 29), true, 2},
     {MONTH_OF_YEAR, LocalDateTime.of(2000, 2, 29, 5, 4, 3, 200), true, 2},
     {DAY_OF_MONTH, LocalDate.of(2000, 2, 29), true, 29},
     {DAY_OF_MONTH, LocalDateTime.of(2000, 2, 29, 5, 4, 3, 200), true, 29},
     {DAY_OF_YEAR, LocalDate.of(2000, 2, 29), true, 60},
     {DAY_OF_YEAR, LocalDateTime.of(2000, 2, 29, 5, 4, 3, 200), true, 60},
     {HOUR_OF_DAY, LocalTime.of(5, 4, 3, 200), true, 5},
     {HOUR_OF_DAY, LocalDateTime.of(2000, 2, 29, 5, 4, 3, 200), true, 5},
     {MINUTE_OF_DAY, LocalTime.of(5, 4, 3, 200), true, 5 * 60 + 4},
     {MINUTE_OF_DAY, LocalDateTime.of(2000, 2, 29, 5, 4, 3, 200), true, 5 * 60 + 4},
     {MINUTE_OF_HOUR, LocalTime.of(5, 4, 3, 200), true, 4},
     {MINUTE_OF_HOUR, LocalDateTime.of(2000, 2, 29, 5, 4, 3, 200), true, 4},
     {SECOND_OF_DAY, LocalTime.of(5, 4, 3, 200), true, 5 * 3600 + 4 * 60 + 3},
     {SECOND_OF_DAY, LocalDateTime.of(2000, 2, 29, 5, 4, 3, 200), true, 5 * 3600 + 4 * 60 + 3},
     {SECOND_OF_MINUTE, LocalTime.of(5, 4, 3, 200), true, 3},
     {SECOND_OF_MINUTE, LocalDateTime.of(2000, 2, 29, 5, 4, 3, 200), true, 3},
     {NANO_OF_SECOND, LocalTime.of(5, 4, 3, 200), true, 200},
     {NANO_OF_SECOND, LocalDateTime.of(2000, 2, 29, 5, 4, 3, 200), true, 200},
     {YEAR, LocalTime.of(5, 4, 3, 200), false, -1},
     {MONTH_OF_YEAR, LocalTime.of(5, 4, 3, 200), false, -1},
     {DAY_OF_MONTH, LocalTime.of(5, 4, 3, 200), false, -1},
     {DAY_OF_YEAR, LocalTime.of(5, 4, 3, 200), false, -1},
     {HOUR_OF_DAY, LocalDate.of(2000, 2, 29), false, -1},
     {MINUTE_OF_DAY, LocalDate.of(2000, 2, 29), false, -1},
     {MINUTE_OF_HOUR, LocalDate.of(2000, 2, 29), false, -1},
     {SECOND_OF_DAY, LocalDate.of(2000, 2, 29), false, -1},
     {SECOND_OF_MINUTE, LocalDate.of(2000, 2, 29), false, -1},
     {NANO_OF_SECOND, LocalDate.of(2000, 2, 29), false, -1},
   };
 }
Exemplo n.º 3
0
  @Override
  public List<Notice> list(String status, LocalDate fromDate, LocalDate toDate, String dongName)
      throws OperationalException {

    try {

      List<Criterion> criteriaList = new ArrayList<>();

      if (!StringUtils.isBlank(status) && !status.equalsIgnoreCase(ALL)) {
        criteriaList.add(Restrictions.eq(STATUS, status));
      }
      if (!StringUtils.isBlank(dongName) && !dongName.equalsIgnoreCase(ALL)) {
        criteriaList.add(Restrictions.eq("dongName", dongName));
      }
      if (fromDate != null) {
        LocalTime time = LocalTime.MIDNIGHT;
        LocalDateTime fromtime = LocalDateTime.of(fromDate, time);
        criteriaList.add(Restrictions.ge(CREATIONDATE, fromtime));
      }
      if (toDate != null) {
        LocalTime time = LocalTime.of(23, 59, 59);
        LocalDateTime totime = LocalDateTime.of(toDate, time);
        criteriaList.add(Restrictions.le(CREATIONDATE, totime));
      }
      criteriaList.add(Restrictions.ne(STATUS, NoticeStatus.DELETED.name()));
      return super.findByCriteria(Notice.class, criteriaList, Order.desc(CREATIONDATE));

    } catch (Exception e) {
      LOGGER.error("list: Exception ", e);
      throw new OperationalException(
          HttpConstants.INTERNAL_SERVER_ERROR,
          ResponseConstants.ERROR_FETCHING_FROM_DB,
          HttpStatus.INTERNAL_SERVER_ERROR);
    }
  }
 @Test
 public void skipsMornings() {
   assertExpectedSlots(
       LocalDateTime.of(2015, Month.AUGUST, 28, 8, 0),
       LocalDateTime.of(2015, Month.AUGUST, 28, 10, 0),
       28,
       9);
 }
 @Test
 public void startOnHourIncludesThatHour() {
   assertExpectedSlots(
       LocalDateTime.of(2015, Month.AUGUST, 27, 9, 0),
       LocalDateTime.of(2015, Month.AUGUST, 27, 10, 0),
       27,
       9);
 }
Exemplo n.º 6
0
 @DataProvider(name = "parseWithoutZoneWithoutOffset")
 Object[][] data_parse_WithoutOffset_WithoutZone() {
   return new Object[][] {
     {"1966-12-31T00:01:10", LocalDateTime.of(1966, 12, 31, 0, 1, 10)},
     {"1970-01-01T00:00:00", LocalDateTime.of(1970, 1, 1, 0, 0, 0)},
     {"2004-02-29T00:30:00", LocalDateTime.of(2004, 2, 29, 0, 30, 0)},
     {"2015-12-31T23:59:59", LocalDateTime.of(2015, 12, 31, 23, 59, 59)}
   };
 }
Exemplo n.º 7
0
 public static void main(String args[]) {
   LocalDateTime dt = LocalDateTime.of(1901, 1, 1, 0, 0);
   LocalDateTime stop = LocalDateTime.of(2000, 12, 31, 0, 0);
   int count = 0;
   while (dt.compareTo(stop) != 0) {
     if (dt.getDayOfMonth() == 1 && dt.getDayOfWeek() == DayOfWeek.SUNDAY) count++;
     dt = dt.plusDays(1);
   }
   System.out.println(count);
 }
 @Test
 public void skipsWeekends() {
   assertExpectedSlots(
       LocalDateTime.of(2015, Month.AUGUST, 28, 16, 0), // Friday
       LocalDateTime.of(2015, Month.AUGUST, 31, 10, 0), // Monday
       28,
       16,
       31,
       9);
 }
Exemplo n.º 9
0
  @Test
  public final void test_get_mixin() throws Exception {
    Mixin mixin =
        Mixin.create()
            .createdTime(LocalDateTime.of(2013, 1, 1, 12, 0, 0).toInstant(ZoneOffset.UTC))
            .name(MY_MIXIN_QUALIFIED_NAME_1.toString())
            .addFormItem(
                Input.create()
                    .name(MY_MIXIN_INPUT_NAME_1)
                    .inputType(InputTypeName.TEXT_LINE)
                    .label("Line Text 1")
                    .required(true)
                    .helpText("Help text line 1")
                    .required(true)
                    .build())
            .build();

    Mockito.when(mixinService.getByName(Mockito.isA(MixinName.class))).thenReturn(mixin);

    String response =
        request()
            .path("schema/mixin")
            .queryParam("name", MY_MIXIN_QUALIFIED_NAME_1.toString())
            .get()
            .getAsString();

    assertJson("get_mixin.json", response);
  }
Exemplo n.º 10
0
  @POST
  @Produces("application/json")
  public Response createOrUpdateGame(
      @FormParam("gameId") Long gameId,
      @FormParam("homeTeam") String homeTeam,
      @FormParam("awayTeam") String awayTeam,
      @FormParam("homeTeamScore") String homeTeamScore,
      @FormParam("awayTeamScore") String awayTeamScore,
      @FormParam("day") Integer day,
      @FormParam("month") Integer month,
      @FormParam("year") Integer year,
      @FormParam("hours") Integer hours,
      @FormParam("minutes") Integer minutes,
      @FormParam("locked") Boolean locked) {
    if (!userContext.getLoggedUser().getIsAdmin()) {
      return Response.status(Response.Status.FORBIDDEN).build();
    }

    Game game = new Game(homeTeam, awayTeam, LocalDateTime.of(year, month, day, hours, minutes));
    game.setId(gameId);
    if (homeTeamScore != null && awayTeamScore != null) {
      game.setResult(homeTeamScore + ":" + awayTeamScore);
    }
    game.setLocked(locked);
    Game storedGame = gamesService.storeGame(game, userContext.getSelectedCompetition());
    return Response.created(URI.create(GAME_RESOURCE_ROOT + "/" + storedGame.getId()))
        .type(MediaType.APPLICATION_JSON_TYPE)
        .entity(storedGame)
        .build();
  }
/** @author <a href="mailto:[email protected]">Lennart J&ouml;relid</a>, jGuru Europe AB */
public class LocalDateTimeAdapterTest {

  private String transportForm = "2015-04-25T15:40:00";
  private LocalDateTime objectForm =
      LocalDateTime.of(LocalDate.of(2015, Month.APRIL, 25), LocalTime.of(15, 40, 0));
  private LocalDateTimeAdapter unitUnderTest = new LocalDateTimeAdapter();

  @Test
  public void validateConvertingToTransportForm() throws Exception {

    // Assemble

    // Act
    final String result = unitUnderTest.marshal(objectForm);
    // System.out.println("Got: " + result);

    // Assert
    Assert.assertNull(unitUnderTest.marshal(null));
    Assert.assertEquals(transportForm, result);
  }

  @Test
  public void validateConvertingFromTransportForm() throws Exception {

    // Assemble

    // Act
    final LocalDateTime result = unitUnderTest.unmarshal(transportForm);

    // Assert
    Assert.assertNull(unitUnderTest.unmarshal(null));
    Assert.assertEquals(objectForm, result);
  }
}
Exemplo n.º 12
0
  public static void main(String[] args) {
    LocalDateTime lDT = LocalDateTime.of(LocalDate.of(2016, 01, 17), LocalTime.of(23, 11, 25));

    System.out.println("The date and time is : " + lDT.toString());
    System.out.println("The strict date is :" + lDT.toLocalDate().toString());
    System.out.println("The strict time is :" + lDT.toLocalTime().toString());
  }
Exemplo n.º 13
0
  public static String getTimeUntilNow(String time) {
    LocalDateTime now = LocalDateTime.now();
    now = now.plusMinutes(1);

    int hours = Integer.parseInt(time.split(":")[0]);
    int minutes = Integer.parseInt(time.split(":")[1]);

    LocalDateTime tocheck =
        LocalDateTime.of(
            now.getYear(),
            now.getMonth(),
            now.getDayOfMonth(),
            hours,
            minutes,
            now.getSecond(),
            now.getNano());

    if (tocheck.isBefore(now)) {
      tocheck = tocheck.plusDays(1);
    }

    Duration remaining = Duration.between(now, tocheck);

    int rh = (int) remaining.toHours();
    int rm = (int) remaining.toMinutes();
    rm %= 60;

    int ht = rh / 10;
    int hs = rh % 10;
    int mt = rm / 10;
    int ms = rm % 10;

    return ht + "" + hs + ":" + mt + "" + ms;
  }
public class ApacheCombinedFormatLoggerTest {
  LogRecordingHandler logRecords = new LogRecordingHandler();
  Instant currentTime = LocalDateTime.of(2012, 6, 27, 12, 4, 0).toInstant(ZoneOffset.of("-05:00"));
  ApacheCombinedFormatLogger apacheCommonLogger =
      new ApacheCombinedFormatLogger(
          anonymousLogger(logRecords), Clock.fixed(currentTime, ZoneId.of("GMT+01:00")), Locale.US);

  Request request = new Request().protocol("HTTP/1.1").remoteIp("192.168.0.1");
  Response response = new Response();

  @Test
  public void logsRequestsServedInApacheCombinedLogFormat() throws Exception {
    request
        .method(GET)
        .uri("/products?keyword=dogs")
        .addHeader(HeaderNames.REFERER, "http://lama/wool")
        .addHeader(HeaderNames.USER_AGENT, "Mozilla/5.0 (compatible; MSIE 9.0; AOL 9.7)");

    apacheCommonLogger.handle(request, response);
    response.status(OK).body("a response with a size of 28").done();

    response.await();
    logRecords.assertEntries(
        contains(
            "192.168.0.1 - - [27/Jun/2012:18:04:00 +0100] \"GET /products?keyword=dogs HTTP/1.1\" 200 28 \"http://lama/wool\" \"Mozilla/5.0 (compatible; MSIE 9.0; AOL 9.7)\""));
  }

  @Test
  public void logsEmptyStringWhenNoUserAgentInRequest() throws Exception {
    request
        .method(GET)
        .uri("/products?keyword=dogs")
        .addHeader(HeaderNames.REFERER, "http://lama/wool");

    apacheCommonLogger.handle(request, response);
    response.status(OK).body("a response with a size of 28").done();

    response.await();
    logRecords.assertEntries(
        contains(
            "192.168.0.1 - - [27/Jun/2012:18:04:00 +0100] \"GET /products?keyword=dogs HTTP/1.1\" 200 28 \"http://lama/wool\" \"\""));
  }

  @Test
  public void logsEmptyStringWhenNoRefererInRequest() throws Exception {
    request
        .method(GET)
        .uri("/products?keyword=dogs")
        .addHeader(HeaderNames.USER_AGENT, "Mozilla/5.0 (compatible; MSIE 9.0; AOL 9.7)");

    apacheCommonLogger.handle(request, response);
    response.status(OK).body("a response with a size of 28").done();

    response.await();
    logRecords.assertEntries(
        contains(
            "192.168.0.1 - - [27/Jun/2012:18:04:00 +0100] \"GET /products?keyword=dogs HTTP/1.1\" 200 28 \"\" \"Mozilla/5.0 (compatible; MSIE 9.0; AOL 9.7)\""));
  }
}
Exemplo n.º 15
0
  private static void useLocalDate() {
    LocalDate date = LocalDate.of(2014, 3, 18);
    int year = date.getYear(); // 2014
    Month month = date.getMonth(); // MARCH
    int day = date.getDayOfMonth(); // 18
    DayOfWeek dow = date.getDayOfWeek(); // TUESDAY
    int len = date.lengthOfMonth(); // 31 (days in March)
    boolean leap = date.isLeapYear(); // false (not a leap year)
    System.out.println(date);

    int y = date.get(ChronoField.YEAR);
    int m = date.get(ChronoField.MONTH_OF_YEAR);
    int d = date.get(ChronoField.DAY_OF_MONTH);

    LocalTime time = LocalTime.of(13, 45, 20); // 13:45:20
    int hour = time.getHour(); // 13
    int minute = time.getMinute(); // 45
    int second = time.getSecond(); // 20
    System.out.println(time);

    LocalDateTime dt1 = LocalDateTime.of(2014, Month.MARCH, 18, 13, 45, 20); // 2014-03-18T13:45
    LocalDateTime dt2 = LocalDateTime.of(date, time);
    LocalDateTime dt3 = date.atTime(13, 45, 20);
    LocalDateTime dt4 = date.atTime(time);
    LocalDateTime dt5 = time.atDate(date);
    System.out.println(dt1);

    LocalDate date1 = dt1.toLocalDate();
    System.out.println(date1);
    LocalTime time1 = dt1.toLocalTime();
    System.out.println(time1);

    Instant instant = Instant.ofEpochSecond(44 * 365 * 86400);
    Instant now = Instant.now();

    Duration d1 = Duration.between(LocalTime.of(13, 45, 10), time);
    Duration d2 = Duration.between(instant, now);
    System.out.println(d1.getSeconds());
    System.out.println(d2.getSeconds());

    Duration threeMinutes = Duration.of(3, ChronoUnit.MINUTES);
    System.out.println(threeMinutes);

    JapaneseDate japaneseDate = JapaneseDate.from(date);
    System.out.println(japaneseDate);
  }
 @Test
 public void testFindByUserIdAndExpireOnGreaterThan() {
   AccessToken accessToken =
       accessTokenRepository.findByUserIdAndExpiresOnGreaterThan(
           1L, Date.from(LocalDateTime.of(2015, 1, 1, 0, 0).toInstant(ZoneOffset.UTC)));
   assertThat(accessToken, is(notNullValue()));
   assertNotNull(accessToken.getUser().getId());
 }
Exemplo n.º 17
0
  public static void main(String[] args) {
    LocalDateTime localDateTime = LocalDateTime.of(2016, 3, 27, 1, 20);
    localDateTime = localDateTime.plusHours(1);
    System.out.println(localDateTime);

    ZoneId zoneId = ZoneId.of("Europe/Warsaw");
    ZonedDateTime zonedDateTime = ZonedDateTime.of(localDateTime, zoneId);
    System.out.println(zonedDateTime);
  }
 @Test
 public void testBindLocalDateTimeAnnotated() {
   MutablePropertyValues propertyValues = new MutablePropertyValues();
   propertyValues.add("localDateTimeAnnotated", LocalDateTime.of(2009, 10, 31, 12, 0));
   binder.bind(propertyValues);
   assertEquals(0, binder.getBindingResult().getErrorCount());
   String value = binder.getBindingResult().getFieldValue("localDateTimeAnnotated").toString();
   assertTrue(value.startsWith("Oct 31, 2009"));
   assertTrue(value.endsWith("12:00:00 PM"));
 }
Exemplo n.º 19
0
  @Test
  public void whenSerializingJava8DateWithCustomSerializer_thenCorrect()
      throws JsonProcessingException {
    final LocalDateTime date = LocalDateTime.of(2014, 12, 20, 2, 30);
    final EventWithLocalDateTime event = new EventWithLocalDateTime("party", date);

    final ObjectMapper mapper = new ObjectMapper();
    final String result = mapper.writeValueAsString(event);
    assertThat(result, containsString("2014-12-20 02:30"));
  }
Exemplo n.º 20
0
 public static void main(String[] args) {
   LocalDate date = LocalDate.of(2015, Month.JULY, 6);
   LocalTime time = LocalTime.of(15, 25);
   LocalDateTime dateTime = LocalDateTime.of(date, time);
   printSectionName("LocalDateTime");
   System.out.println(dateTime);
   System.out.println(dateTime.minusDays(1));
   System.out.println(dateTime.minusHours(5));
   System.out.println(dateTime.minusSeconds(7));
   printDelimiterString();
 }
Exemplo n.º 21
0
  @Test
  public void whenSerializingJava8Date_thenCorrect() throws JsonProcessingException {
    final LocalDateTime date = LocalDateTime.of(2014, 12, 20, 2, 30);

    final ObjectMapper mapper = new ObjectMapper();
    mapper.registerModule(new JSR310Module());
    mapper.disable(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS);

    final String result = mapper.writeValueAsString(date);
    assertThat(result, containsString("2014-12-20T02:30"));
  }
  @Test
  public void shouldGenerateTokenForUser() {
    // given
    final WebsUser websUser = new WebsUserBuilder().id(1).build();
    given(dateSupplier.get()).willReturn(LocalDateTime.of(2014, 11, 26, 0, 0));
    given(uuidGenerator.generate()).willReturn("a9f4411a-7205-472b-8be5-ddd17108b45b");
    given(tokenRepository.save(any(PasswordResetToken.class)))
        .willAnswer(invocation -> invocation.getArguments()[0]);

    // when
    final PasswordResetToken passwordResetToken =
        tokenGenerator.generateAndStoreTokenForUser(websUser);

    // then
    assertThat(passwordResetToken)
        .hasUserId(1)
        .hasCreatedAt(LocalDateTime.of(2014, 11, 26, 0, 0))
        .hasIsExpired(false)
        .hasTokenId("a9f4411a-7205-472b-8be5-ddd17108b45b");
  }
  private LocalDateTime makeDateTime(String date, String time) {
    String[] splitDate = date.split("\\.");
    String[] splitTime = time.split(":");

    int dayOfMonth = Integer.parseInt(splitDate[0]);
    int month = Integer.parseInt(splitDate[1]);
    int year = Integer.parseInt(splitDate[2]);
    int hour = Integer.parseInt(splitTime[0]);
    int minute = Integer.parseInt(splitTime[1]);

    return LocalDateTime.of(year, month, dayOfMonth, hour, minute);
  }
Exemplo n.º 24
0
 private static LocalDateTime parseJavaLocalDateTimeUI(String str) {
   // First parse to Joda DateTime for timezone calculation
   DateTime dateTime = DTF.parseDateTime(str);
   // Then create LocalDateTime from Joda DateTime and return it
   return LocalDateTime.of(
       dateTime.getYear(),
       dateTime.getMonthOfYear(),
       dateTime.getDayOfMonth(),
       dateTime.getHourOfDay(),
       dateTime.getMinuteOfHour(),
       dateTime.getSecondOfMinute());
 }
  @Test
  public void should_create_year_histogram() {
    // given
    final StreamDateHistogramStatistics stats = new StreamDateHistogramStatistics();
    stats.setNumberOfBins(4);

    stats.add(LocalDateTime.of(2013, JANUARY, 5, 8, 8));
    stats.add(LocalDateTime.of(2015, JANUARY, 6, 9, 9));
    stats.add(LocalDateTime.of(2015, MARCH, 15, 0, 0));
    stats.add(LocalDateTime.of(2013, APRIL, 1, 12, 12));
    stats.add(LocalDateTime.of(2015, MARCH, 25, 4, 10));
    stats.add(LocalDateTime.of(2015, JANUARY, 5, 7, 9));

    // when
    final Histogram histogram = stats.getHistogram();

    // then
    assertThat(((DateHistogram) histogram).getPace(), is(DateManipulator.Pace.YEAR));
    assertThat(histogram.getItems().size(), is(3));

    HistogramRange histoRange = histogram.getItems().get(0);
    assertThat((long) histoRange.getRange().getMin(), is(1356998400000L));
    assertThat((long) histoRange.getRange().getMax(), is(1388534400000L));
    assertThat(histoRange.getOccurrences(), is(2L));

    histoRange = histogram.getItems().get(1);
    assertThat((long) histoRange.getRange().getMin(), is(1388534400000L));
    assertThat((long) histoRange.getRange().getMax(), is(1420070400000L));
    assertThat(histoRange.getOccurrences(), is(0L));

    histoRange = histogram.getItems().get(2);
    assertThat((long) histoRange.getRange().getMin(), is(1420070400000L));
    assertThat((long) histoRange.getRange().getMax(), is(1451606400000L));
    assertThat(histoRange.getOccurrences(), is(4L));
  }
  @Test
  public void should_create_day_histogram() {
    // given
    final StreamDateHistogramStatistics stats = new StreamDateHistogramStatistics();
    stats.setNumberOfBins(4);

    stats.add(LocalDateTime.of(2015, JANUARY, 5, 5, 6, 7));
    stats.add(LocalDateTime.of(2015, JANUARY, 6, 0, 0, 0));
    stats.add(LocalDateTime.of(2015, JANUARY, 7, 12, 58, 0));
    stats.add(LocalDateTime.of(2015, JANUARY, 6, 2, 4, 45));
    stats.add(LocalDateTime.of(2015, JANUARY, 5, 3, 45, 2));
    stats.add(LocalDateTime.of(2015, JANUARY, 5, 9, 8, 3));

    // when
    final Histogram histogram = stats.getHistogram();

    // then
    assertThat(((DateHistogram) histogram).getPace(), is(DateManipulator.Pace.DAY));
    assertThat(histogram.getItems().size(), is(3));

    HistogramRange histoRange = histogram.getItems().get(0);
    assertThat((long) histoRange.getRange().getMin(), is(1420416000000L));
    assertThat((long) histoRange.getRange().getMax(), is(1420502400000L));
    assertThat(histoRange.getOccurrences(), is(3L));

    histoRange = histogram.getItems().get(1);
    assertThat((long) histoRange.getRange().getMin(), is(1420502400000L));
    assertThat((long) histoRange.getRange().getMax(), is(1420588800000L));
    assertThat(histoRange.getOccurrences(), is(2L));

    histoRange = histogram.getItems().get(2);
    assertThat((long) histoRange.getRange().getMin(), is(1420588800000L));
    assertThat((long) histoRange.getRange().getMax(), is(1420675200000L));
    assertThat(histoRange.getOccurrences(), is(1L));
  }
Exemplo n.º 27
0
 @Test
 public void newPromotionRun_with_date() throws Exception {
   PromotionRun promotionRunToCreate =
       PromotionRun.of(
           build,
           copper,
           Signature.of("test").withTime(LocalDateTime.of(2014, 9, 13, 18, 24)),
           "");
   when(structureRepository.newPromotionRun(promotionRunToCreate))
       .thenReturn(promotionRunToCreate.withId(ID.of(1)));
   service.newPromotionRun(promotionRunToCreate);
   verify(structureRepository, times(1)).newPromotionRun(promotionRunToCreate);
 }
 @Test
 public void testBindDateTimeWithSpecificStyle() throws Exception {
   DateTimeFormatterRegistrar registrar = new DateTimeFormatterRegistrar();
   registrar.setDateTimeStyle(FormatStyle.MEDIUM);
   setUp(registrar);
   MutablePropertyValues propertyValues = new MutablePropertyValues();
   propertyValues.add("localDateTime", LocalDateTime.of(2009, 10, 31, 12, 0));
   binder.bind(propertyValues);
   assertEquals(0, binder.getBindingResult().getErrorCount());
   String value = binder.getBindingResult().getFieldValue("localDateTime").toString();
   assertTrue(value.startsWith("Oct 31, 2009"));
   assertTrue(value.endsWith("12:00:00 PM"));
 }
Exemplo n.º 29
0
  @Test
  public void testLocalDateTime() {
    System.out.println(LocalDateTime.now());
    System.out.println(LocalDateTime.of(1994, Month.MAY, 15, 11, 30));
    System.out.println(LocalDateTime.ofInstant(Instant.now(), ZoneId.systemDefault()));
    System.out.println(LocalDateTime.ofEpochSecond(1450749600, 0, ZoneOffset.ofHours(8)));

    System.out.printf("6 months from now: %s%n", LocalDateTime.now().plusMonths(6));
    System.out.printf("6 days ago: %s%n", LocalDateTime.now().minusDays(6));

    System.out.println(DateTimeFormatter.ISO_DATE_TIME.format(LocalDateTime.now()));
    System.out.println(DateTimeFormatter.ofPattern("MM-dd HH:mm").format(LocalDateTime.now()));
  }
  public static void main(String[] args) {
    LocalDateTime date1 = LocalDateTime.of(LocalDate.of(1999, 5, 15), LocalTime.of(10, 22));
    LocalDateTime date2 = LocalDateTime.of(LocalDate.of(2008, 2, 11), LocalTime.of(5, 33));
    System.out.println("date1: " + date1);
    System.out.println("date2: " + date2);

    System.out.println(ChronoUnit.YEARS.between(date1, date2));
    System.out.println(ChronoUnit.MONTHS.between(date1, date2));
    System.out.println(ChronoUnit.WEEKS.between(date1, date2));
    System.out.println(ChronoUnit.DAYS.between(date1, date2));
    System.out.println(ChronoUnit.HOURS.between(date1, date2));
    System.out.println(ChronoUnit.MINUTES.between(date1, date2));
    System.out.println(ChronoUnit.SECONDS.between(date1, date2));
  }