Java Code Examples for java.time.LocalDateTime

The following are top voted examples for showing how to use java.time.LocalDateTime. These examples are extracted from open source projects. You can vote up the examples you like and your votes will be used in our system to generate more good examples.
Example 1
Project: Botico2   File: BTimeoutManager.java   View source code 6 votes vote down vote up
public void setTimeout(String id, LocalDateTime to)
{
    try(Connection conn = botico.sql.connect())
    {
        try(PreparedStatement st = conn.prepareStatement("INSERT OR REPLACE INTO `timeouts` (`id`, `expiresIn`) VALUES(?, ?);"))
        {
            st.setString(1, id);
            st.setTimestamp(2, Timestamp.valueOf(to));
            st.executeUpdate();
        }
    }
    catch (SQLException e)
    {
        botico.log.error("Can't set timeout!", e);
    }
}
 
Example 2
Project: uroborosql   File: DateTimeApiPropertyMapper.java   View source code 6 votes vote down vote up
@Override
public boolean canAccept(final Class<?> type) {
	return LocalDateTime.class.equals(type)
			|| OffsetDateTime.class.equals(type)
			|| ZonedDateTime.class.equals(type)
			|| LocalDate.class.equals(type)
			|| LocalTime.class.equals(type)
			|| OffsetTime.class.equals(type)
			|| Year.class.equals(type)
			|| YearMonth.class.equals(type)
			|| MonthDay.class.equals(type)
			|| Month.class.equals(type)
			|| DayOfWeek.class.equals(type)
			|| checkEra(type)
			|| checkChronoLocalDate(type);
}
 
Example 3
Project: grittier_ext   File: Users.java   View source code 6 votes vote down vote up
public static Node getPost(Node author, Long time) {
    LocalDateTime postedDateTime = LocalDateTime.ofEpochSecond(time, 0, ZoneOffset.UTC);
    RelationshipType original = RelationshipType.withName("POSTED_ON_" +
            postedDateTime.format(dateFormatter));
    Node post = null;
    for(Relationship r1 : author.getRelationships(Direction.OUTGOING, original)) {
        Node potential = r1.getEndNode();
        if (time.equals(potential.getProperty(TIME))) {
            post = potential;
            break;
        }
    }
    if(post == null) { throw PostExceptions.postNotFound; };

    return post;
}
 
Example 4
Project: pokeraidbot   File: Utils.java   View source code 6 votes vote down vote up
public static void assertCreateRaidTimeNotBeforeNow(User user, LocalDateTime dateAndTime,
                                                    LocaleService localeService) {
    final LocalDateTime now = clockService.getCurrentDateTime();
    if (dateAndTime.isBefore(now)) {
        throw new UserMessedUpException(user,
                localeService.getMessageFor(LocaleService.TIMEZONE, localeService.getLocaleForUser(user),
                        printTimeIfSameDay(dateAndTime), printTimeIfSameDay(now)));
    }
}
 
Example 5
Project: openjdk-jdk10   File: TCKLocalDateTime.java   View source code 6 votes vote down vote up
@Test
public void test_plusHours_fromZero() {
    LocalDateTime base = TEST_2007_07_15_12_30_40_987654321.with(LocalTime.MIDNIGHT);
    LocalDate d = base.toLocalDate().minusDays(3);
    LocalTime t = LocalTime.of(21, 0);

    for (int i = -50; i < 50; i++) {
        LocalDateTime dt = base.plusHours(i);
        t = t.plusHours(1);

        if (t.getHour() == 0) {
            d = d.plusDays(1);
        }

        assertEquals(dt.toLocalDate(), d);
        assertEquals(dt.toLocalTime(), t);
    }
}
 
Example 6
Project: minsx-framework   File: AddTest.java   View source code 6 votes vote down vote up
@Test
public void addUser() {
    User user = new User();
    user.setUserName("goodsave");
    user.setPassWord(passwordEncoder.encode("goodsave"));
    user.setEmail("[email protected]");
    user.setFace(null);
    user.setLastLoginTime(LocalDateTime.now());
    user.setPhone("15505090507");
    user.setRegisterIp("192.168.1.1");
    user.setLastLoginIp("192.168.1.1");
    user.setRegisterTime(LocalDateTime.now());
    user.setSignature("hi goodsave");
    user.setState(UserState.NORMAL);
    user.setUserNick("xiaochun");
    user.setGroups(groupRepository.findAll());
    userRepository.saveAndFlush(user);
}
 
Example 7
Project: jdk8u-jdk   File: TCKZoneRules.java   View source code 6 votes vote down vote up
public void test_NewYork_getOffsetInfo_overlap() {
    ZoneRules test = americaNewYork();
    final LocalDateTime dateTime = LocalDateTime.of(2008, 11, 2, 1, 0, 0, 0);
    ZoneOffsetTransition trans = checkOffset(test, dateTime, ZoneOffset.ofHours(-4), OVERLAP);
    assertEquals(trans.isGap(), false);
    assertEquals(trans.isOverlap(), true);
    assertEquals(trans.getOffsetBefore(), ZoneOffset.ofHours(-4));
    assertEquals(trans.getOffsetAfter(), ZoneOffset.ofHours(-5));
    assertEquals(trans.getInstant(), createInstant(2008, 11, 2, 2, 0, ZoneOffset.ofHours(-4)));
    assertEquals(trans.isValidOffset(ZoneOffset.ofHours(-1)), false);
    assertEquals(trans.isValidOffset(ZoneOffset.ofHours(-5)), true);
    assertEquals(trans.isValidOffset(ZoneOffset.ofHours(-4)), true);
    assertEquals(trans.isValidOffset(OFFSET_PTWO), false);
    assertEquals(trans.toString(), "Transition[Overlap at 2008-11-02T02:00-04:00 to -05:00]");

    assertFalse(trans.equals(null));
    assertFalse(trans.equals(ZoneOffset.ofHours(-4)));
    assertTrue(trans.equals(trans));

    final ZoneOffsetTransition otherTrans = test.getTransition(dateTime);
    assertTrue(trans.equals(otherTrans));
    assertEquals(trans.hashCode(), otherTrans.hashCode());
}
 
Example 8
Project: tenhou-visualizer   File: DatabaseService.java   View source code 6 votes vote down vote up
@NotNull
public List<InfoSchema> findAllExistsInfos() {
    try (ResultSet rs = this.findAllExistsInfoStatement.executeQuery()) {
        List<InfoSchema> list = new ArrayList<>();
        while (rs.next()) {
            list.add(new InfoSchema.Builder(
                    rs.getString("id"),
                    rs.getInt("is_sanma") == 1,
                    rs.getInt("is_tonnan") == 1,
                    LocalDateTime.from(DateTimeFormatter.ISO_LOCAL_DATE_TIME.parse(rs.getString("date_time"))),
                    rs.getString("first"),
                    rs.getString("second"),
                    rs.getString("third"),
                    rs.getString("fourth")
            ).build());
        }
        return list;
    } catch (SQLException e) {
        throw new RuntimeException();
    }
}
 
Example 9
Project: willtest   File: WebDriverLog.java   View source code 6 votes vote down vote up
private void processWebDriverLogs(WebDriver webDriver) {
    Logs logs = webDriver.manage().logs();
    for (String logType : WEBDRIVER_LOG_LEVELS.keySet()) {
        LOGGER.info("Dumping webdriver log for log type " + logType);
        LogEntries logEntries = logs.get(logType);
        for (LogEntry logEntry : logEntries) {
            String formattedOriginalTimestamp = LOG_TIMESTAMP_FORMAT
                    .format(LocalDateTime.ofInstant(Instant.ofEpochMilli(logEntry.getTimestamp()), ZoneOffset.UTC));
            Level logEntryLevel = logEntry.getLevel();
            if (logEntryLevel.equals(Level.FINE)) {
                LOGGER.debug(MESSAGE_PATTERN, logType, formattedOriginalTimestamp, logEntry.getMessage());
            } else if (logEntryLevel.equals(Level.INFO)) {
                LOGGER.info(MESSAGE_PATTERN, logType, formattedOriginalTimestamp, logEntry.getMessage());
            } else if (logEntryLevel.equals(Level.WARNING)) {
                LOGGER.warn(MESSAGE_PATTERN, logType, formattedOriginalTimestamp, logEntry.getMessage());
            } else if (logEntryLevel.equals(Level.SEVERE)) {
                LOGGER.error(MESSAGE_PATTERN, logType, formattedOriginalTimestamp, logEntry.getMessage());
            } else if (logEntryLevel.equals(Level.FINER)) {
                LOGGER.trace(MESSAGE_PATTERN, logType, formattedOriginalTimestamp, logEntry.getMessage());
            }
        }
    }
}
 
Example 10
Project: openjdk-jdk10   File: TCKDateTimeFormatterBuilder.java   View source code 6 votes vote down vote up
@DataProvider(name = "formatNonGenericTimeZonePatterns_2")
Object[][]  data_formatNonGenericTimeZonePatterns_2() {
    return new Object[][] {
            {"yyyy-MM-dd HH:mm:ss z", LocalDateTime.of(2015, Month.NOVEMBER, 1, 0, 30),
             "2015-11-01 00:30:00 PDT"},
            {"yyyy-MM-dd HH:mm:ss z", LocalDateTime.of(2015, Month.NOVEMBER, 1, 1, 30),
             "2015-11-01 01:30:00 PT"},
            {"yyyy-MM-dd HH:mm:ss z", LocalDateTime.of(2015, Month.NOVEMBER, 1, 2, 30),
             "2015-11-01 02:30:00 PST"},
            {"yyyy-MM-dd HH:mm:ss zzzz", LocalDateTime.of(2015, Month.NOVEMBER, 1, 0, 30),
             "2015-11-01 00:30:00 Pacific Daylight Time"},
            {"yyyy-MM-dd HH:mm:ss zzzz", LocalDateTime.of(2015, Month.NOVEMBER, 1, 1, 30),
             "2015-11-01 01:30:00 Pacific Time"},
            {"yyyy-MM-dd HH:mm:ss zzzz", LocalDateTime.of(2015, Month.NOVEMBER, 1, 2, 30),
             "2015-11-01 02:30:00 Pacific Standard Time"},
    };
}
 
Example 11
Project: morpheus-core   File: IndexFactoryDefault.java   View source code 6 votes vote down vote up
@Override
@SuppressWarnings("unchecked")
public <K> Index<K> create(Class<K> keyType, int initialSize) {
    switch (ArrayType.of(keyType)) {
        case INTEGER:           return (Index<K>)new IndexOfInts(initialSize);
        case LONG:              return (Index<K>)new IndexOfLongs(initialSize);
        case DOUBLE:            return (Index<K>)new IndexOfDoubles(initialSize);
        case STRING:            return (Index<K>)new IndexOfStrings(initialSize);
        case YEAR:              return (Index<K>)new IndexWithIntCoding<>((Class<Year>)keyType, yearCoding, initialSize);
        case DATE:              return (Index<K>)new IndexWithLongCoding<>((Class<Date>)keyType, dateCoding, initialSize);
        case INSTANT:           return (Index<K>)new IndexWithLongCoding<>((Class<Instant>)keyType, instantCoding, initialSize);
        case LOCAL_DATE:        return (Index<K>)new IndexWithLongCoding<>((Class<LocalDate>)keyType, localDateCoding, initialSize);
        case LOCAL_TIME:        return (Index<K>)new IndexWithLongCoding<>((Class<LocalTime>)keyType, localTimeCoding, initialSize);
        case LOCAL_DATETIME:    return (Index<K>)new IndexWithLongCoding<>((Class<LocalDateTime>)keyType, localDateTimeCoding, initialSize);
        case ZONED_DATETIME:    return (Index<K>)new IndexWithLongCoding<>((Class<ZonedDateTime>)keyType, zonedDateTimeCoding, initialSize);
        default:                return new IndexOfObjects<>(keyType, initialSize);
    }
}
 
Example 12
Project: Syn   File: VerifierTest.java   View source code 6 votes vote down vote up
@Test
public void testClaimsAndVerifyHmac() throws Exception {
    token = JWT.create()
            .withArrayClaim("roles", new String[]{"Role1", "Role2"})
            .withClaim("uid", 1)
            .withClaim("name", "admin")
            .withClaim("url", "http://test.com")
            .withIssuedAt(Date.from(LocalDateTime.now().toInstant(offset)))
            .withExpiresAt(Date.from(LocalDateTime.now().plusHours(2).toInstant(offset)))
            .sign(Algorithm.HMAC256("secret"));

    final Verifier verifier = Verifier.create(token);
    assertEquals(1, verifier.getUid());
    assertEquals("admin", verifier.getName());
    assertEquals("http://test.com", verifier.getUrl());
    final List<String> roles = verifier.getRoles();
    assertEquals(2, roles.size());
    assertEquals("Role1", roles.get(0));
    assertEquals("Role2", roles.get(1));

    assertTrue(verifier.verify(Algorithm.HMAC256("secret")));
    assertFalse(verifier.verify(Algorithm.HMAC256("wrong secret")));
}
 
Example 13
Project: betleopard   File: Race.java   View source code 5 votes vote down vote up
private RaceDetails(long ID) {
    id = ID;
    odds = new HashMap<>();
    raceTime = LocalDateTime.MIN;
    version = 1;
    winner = Optional.empty();
}
 
Example 14
Project: jdk8u-jdk   File: TCKZoneOffsetTransition.java   View source code 5 votes vote down vote up
@Test
public void test_getters_overlap() throws Exception {
    LocalDateTime before = LocalDateTime.of(2010, 10, 31, 1, 0);
    LocalDateTime after = LocalDateTime.of(2010, 10, 31, 0, 0);
    ZoneOffsetTransition test = ZoneOffsetTransition.of(before, OFFSET_0300, OFFSET_0200);
    assertEquals(test.isGap(), false);
    assertEquals(test.isOverlap(), true);
    assertEquals(test.getDateTimeBefore(), before);
    assertEquals(test.getDateTimeAfter(), after);
    assertEquals(test.getInstant(), before.toInstant(OFFSET_0300));
    assertEquals(test.getOffsetBefore(), OFFSET_0300);
    assertEquals(test.getOffsetAfter(), OFFSET_0200);
    assertEquals(test.getDuration(), Duration.of(-1, HOURS));
}
 
Example 15
Project: rulesservice   File: QRules.java   View source code 5 votes vote down vote up
public LocalDateTime getBaseEntityValueAsLocalDateTime(final String baseEntityCode, final String attributeCode) {
	BaseEntity be = getBaseEntityByCode(baseEntityCode);
	Optional<EntityAttribute> ea = be.findEntityAttribute(attributeCode);
	if (ea.isPresent()) {
		return ea.get().getValueDateTime();
	} else {
		return null;
	}
}
 
Example 16
Project: VoxelGamesLibv2   File: AbstractPhase.java   View source code 5 votes vote down vote up
@Override
@Nonnull
public Duration getDuration() {
    if (duration == null) {
        return Duration.between(startTime, LocalDateTime.now());
    } else {
        return duration;
    }
}
 
Example 17
Project: JSK   File: JSKDateConverter.java   View source code 5 votes vote down vote up
/**
 * This method returns the date passed as parameter converted to {@link Date}
 * @param date {@link LocalDateTime}
 * @return {@link Date}
 * @throws JSKException if some of the parameters are null.
 */
public static Date dateToDate(LocalDateTime date) throws JSKException {
	
	if (isNull(date)) {
           throw new JSKException(NULL_PARAMETERS);
       }
	
	return Date.from(date.atZone(ZoneId.systemDefault()).toInstant());
}
 
Example 18
Project: cakes   File: PerformanceTest4Business.java   View source code 5 votes vote down vote up
/**
 * 使用并行流
 * channel=127, sum amount=2999937
 * channel=128, sum amount=2999940
 * channel=129, sum amount=2999940
 * channel=130, sum amount=2999940
 * channel=131, sum amount=2999940
 * cost time:440
 */
@Test
public void testParallelStream() {
    List<Order> list = Lists.newArrayList();

    for (int i = 0; i < size; i++) {
        Order o = new Order(i, "success", 3, i % 5 + 127, "12112121223", "jim", "18612534462", LocalDateTime.now().minusDays(12), LocalDateTime.now());
        list.add(o);
    }

    Instant start = Instant.now();

    list.parallelStream().collect(Collectors.groupingBy(Order::getChannelId)).entrySet()
            .parallelStream()
            .collect(Collectors.toMap(Map.Entry::getKey, element -> element.getValue()
                    .parallelStream()
                    .filter(order -> order.getOrderId() > 100)
                    .filter(order -> order.getUserName().equals("jim"))
                    .collect(Collectors.summingLong(Order::getAmount))))
            .entrySet()
            .forEach(data -> {
                System.out.println("channel=" + data.getKey() + ", sum amount=" + data.getValue());
            });

    Instant end = Instant.now();
    long millis = Duration.between(start, end).toMillis();
    System.out.println("cost time:" + millis);
}
 
Example 19
Project: zerocell   File: CellMethodSpec.java   View source code 5 votes vote down vote up
public static String converterStatementFor(ColumnInfoType column) {
    String fieldType = String.format("%s", column.getType());

    if (fieldType.equals(LocalDateTime.class.getTypeName())) {
        return "cur.set$L(toLocalDateTime.convert(formattedValue, $S, currentRow))";

    } else if (fieldType.equals(LocalDate.class.getTypeName())) {
        return "cur.set$L(toLocalDate.convert(formattedValue, $S, currentRow))";

    } else if (fieldType.equals(java.sql.Date.class.getTypeName())) {
        return "cur.set$L(toSqlDate.convert(formattedValue, $S, currentRow))";

    } else if (fieldType.equals(Timestamp.class.getTypeName())) {
        return "cur.set$L(toSqlTimestamp.convert(formattedValue, $S, currentRow))";

    } else if (fieldType.equals(Integer.class.getTypeName()) ||
            fieldType.equals(int.class.getTypeName())) {
        return "cur.set$L(toInteger.convert(formattedValue, $S, currentRow))";

    } else if (fieldType.equals(Long.class.getTypeName()) ||
            fieldType.equals(long.class.getTypeName())) {
        return "cur.set$L(toLong.convert(formattedValue, $S, currentRow))";

    } else if (fieldType.equals(Double.class.getTypeName()) ||
            fieldType.equals(double.class.getTypeName())) {
        return "cur.set$L(toDouble.convert(formattedValue, $S, currentRow))";

    } else if (fieldType.equals(Float.class.getTypeName()) ||
            fieldType.equals(float.class.getTypeName())) {
        return "cur.set$L(toFloat.convert(formattedValue, $S, currentRow))";

    } else if (fieldType.equals(Boolean.class.getTypeName())) {
        return "cur.set$L(toBoolean.convert(formattedValue, $S, currentRow))";
    }
    // Default to Converters.noop.convert
    return "cur.set$L(noop.convert(formattedValue, $S, currentRow))";
}
 
Example 20
Project: alphavantage4j   File: TechnicalIndicatorParser.java   View source code 5 votes vote down vote up
/**
 * Helper method for resolving local date time. If the key to the data object doesn´t specify hours and minutes it
 * returns the hour at beginning of that day.
 *
 * @param key the key to the data object, i.e: "2017-12-01 11:15" or "2017-12-01" depending on interval
 * @return the {@link LocalDateTime} instance
 */
protected LocalDateTime resolveDate(String key) {
  switch (interval) {
    case MONTHLY:
    case WEEKLY:
    case DAILY:
      return LocalDate.parse(key, SIMPLE_DATE_FORMAT).atStartOfDay();
    default:
      return LocalDateTime.parse(key, DATE_WITH_SIMPLE_TIME_FORMAT);
  }
}
 
Example 21
Project: Supreme-Bot   File: GuildLogger.java   View source code 5 votes vote down vote up
@Override
public void onGuildLeave(GuildLeaveEvent event) {
    final Instant timestamp = Instant.now();
    if (Standard.getConsoleTextChannel() != null) {
        Standard.getConsoleTextChannel().sendMessage(String.format("[%s] Left guild %s", LocalDateTime.ofInstant(timestamp, getZoneId()).format(DateTimeFormatter.ofPattern(Standard.STANDARD_DATE_TIME_FORMAT)), Standard.getCompleteName(event.getGuild()))).queue();
    }
}
 
Example 22
Project: alphavantage4j   File: TechnicalIndicatorsTest.java   View source code 5 votes vote down vote up
@Test
public void aroon() {
  String json = "" +
          "{\n" +
          "    \"Meta Data\": {\n" +
          "        \"1: Symbol\": \"DUMMY\",\n" +
          "        \"2: Indicator\": \"Aroon (AROON)\",\n" +
          "        \"3: Last Refreshed\": \"2017-12-14\",\n" +
          "        \"4: Interval\": \"daily\",\n" +
          "        \"5: Time Period\": 14,\n" +
          "        \"6: Time Zone\": \"US/Eastern Time\"\n" +
          "    },\n" +
          "    \"Technical Analysis: AROON\": {\n" +
          "        \"2000-01-24\": {\n" +
          "            \"Aroon Up\": \"0.0000\",\n" +
          "            \"Aroon Down\": \"100.0000\"\n" +
          "        }\n" +
          "    }\n" +
          "}";
  technicalIndicators = new TechnicalIndicators(apiParameters -> json);
  AROON response = technicalIndicators.aroon("DUMMY", Interval.DAILY, TimePeriod.of(14));

  List<AROONData> indicatorData = response.getData();
  assertThat(indicatorData.size(), is(equalTo(1)));

  AROONData data = indicatorData.get(0);
  assertThat(data.getDateTime(), is(equalTo(LocalDateTime.of(2000, 1, 24, 0, 0))));
  assertThat(data.getAroonUp(), is(equalTo(0.0000d)));
  assertThat(data.getAroonDown(), is(equalTo(100.0000d)));
}
 
Example 23
Project: Simplify-Core   File: TemporalCodec.java   View source code 5 votes vote down vote up
@Override
public Object parse(Object o, Method m) {
    Class<?> parameterTypes = getParameterTypes(m);
    if (LocalDate.class == parameterTypes) {
        return LocalDate.parse(o.toString());
    } else if (LocalDateTime.class == parameterTypes) {
        return LocalDateTime.parse(o.toString(), DateTimeFormatterExt.ISO_LOCAL_DATE_TIME);
    } else if (LocalTime.class == parameterTypes) {
        return LocalTime.parse(o.toString());
    }
    return null;
}
 
Example 24
Project: moviediary   File: StringUtils.java   View source code 5 votes vote down vote up
/**
 * Returns String representing given LocalDateTime.
 *
 * @param date to format
 * @return date as string
 */
public static String getNormalDate(LocalDateTime date, int type) {
    String returnString = date.getDayOfMonth() + " " + date.getMonth().toString().substring(0, 1).toUpperCase();
    return returnString + (type == SHORT_DATE ?
            date.getMonth().toString().substring(1, 3).toLowerCase() :
            date.getMonth().toString().substring(1).toLowerCase()) +
            " " + date.getYear();
}
 
Example 25
Project: DeBrug   File: Rechtsbetrekking__BehaviorDescriptor.java   View source code 5 votes vote down vote up
@Override
protected <T> T invokeSpecial0(@NotNull SNode node, @NotNull SMethod<T> method, @Nullable Object[] parameters) {
  int methodIndex = BH_METHODS.indexOf(method);
  if (methodIndex < 0) {
    throw new BHMethodNotFoundException(this, method);
  }
  switch (methodIndex) {
    case 0:
      return (T) ((Boolean) IsGeldigOpDatumTijdstip_id2mYdLn7TluB(node, (LocalDateTime) parameters[0]));
    case 1:
      return (T) ((String) OntstaanDoor_id6oAJqs3xsei(node));
    default:
      throw new BHMethodNotFoundException(this, method);
  }
}
 
Example 26
Project: dummymaker   File: UniqueGeneratorsTest.java   View source code 5 votes vote down vote up
@Test
public void localDateTimeGen() {
    IGenerator generator = new LocalDateTimeGenerator();

    Object generated = generator.generate();

    assertNotNull(generated);
    assertTrue(generated.getClass().equals(LocalDateTime.class));
}
 
Example 27
Project: jdk8u-jdk   File: TestLocalDateTime.java   View source code 5 votes vote down vote up
void test_comparisons_LocalDateTime(LocalDate[] localDates, LocalTime... localTimes) {
    LocalDateTime[] localDateTimes = new LocalDateTime[localDates.length * localTimes.length];
    int i = 0;

    for (LocalDate localDate : localDates) {
        for (LocalTime localTime : localTimes) {
            localDateTimes[i++] = LocalDateTime.of(localDate, localTime);
        }
    }

    doTest_comparisons_LocalDateTime(localDateTimes);
}
 
Example 28
Project: bson-codecs-jsr310   File: LocalDateTimeCodec.java   View source code 5 votes vote down vote up
@Override
public void encode(
        BsonWriter writer,
        LocalDateTime value,
        EncoderContext encoderContext) {

    writer.writeDateTime(
            value.toInstant(UTC)
                 .toEpochMilli()
    );
}
 
Example 29
Project: ndbc   File: EncodingTest.java   View source code 5 votes vote down vote up
@Test
public void localDateTimeArray() throws CheckedFutureException {
  test("timestamp[]", (ps, v) -> ps.setLocalDateTimeArray(v), Value::getLocalDateTimeArray, r -> {
    LocalDateTime[] array = new LocalDateTime[r.nextInt(10)];
    for(int i = 0; i < array.length; i++) 
      array[i] = randomLocalDateTime(r);
    return array;
  }, (a, b) -> assertArrayEquals(a, b));
}
 
Example 30
Project: nymph   File: DateUtil.java   View source code 5 votes vote down vote up
/**
 * 将Date解析成指定格式的字符串
 * @param date
 * @param format
 * @return
 */
public static String resolve(Date date, String format) {
	Instant milli = Instant.ofEpochMilli(date.getTime());
	LocalDateTime ofInstant = LocalDateTime.ofInstant(milli, ZoneId.of("Asia/Shanghai"));
	DateTimeFormatter formatter = DateTimeFormatter.ofPattern(format);
	return ofInstant.format(formatter);
}
 
Example 31
Project: openjdk-jdk10   File: TCKZoneOffsetTransitionRule.java   View source code 5 votes vote down vote up
@Test
public void test_createTransition_floatingWeekBackwards_last() {
    ZoneOffsetTransitionRule test = ZoneOffsetTransitionRule.of(
            Month.MARCH, -1, DayOfWeek.SUNDAY, TIME_0100, false, TimeDefinition.WALL,
            OFFSET_0200, OFFSET_0200, OFFSET_0300);
    ZoneOffsetTransition trans = ZoneOffsetTransition.of(
            LocalDateTime.of(2000, Month.MARCH, 26, 1, 0), OFFSET_0200, OFFSET_0300);
    assertEquals(test.createTransition(2000), trans);
}
 
Example 32
Project: hekate   File: HekateTestBase.java   View source code 5 votes vote down vote up
protected static void sayHeader(Object msg) {
    String sep = System.lineSeparator();

    System.out.println(sep
        + "***************************" + sep
        + "*** [" + TIMESTAMP_FORMAT.format(LocalDateTime.now()) + "]: " + msg + sep
        + "***************************"
    );
}
 
Example 33
Project: openjdk-jdk10   File: TCKZoneOffsetTransition.java   View source code 5 votes vote down vote up
@Test
public void test_getters_overlap() throws Exception {
    LocalDateTime before = LocalDateTime.of(2010, 10, 31, 1, 0);
    LocalDateTime after = LocalDateTime.of(2010, 10, 31, 0, 0);
    ZoneOffsetTransition test = ZoneOffsetTransition.of(before, OFFSET_0300, OFFSET_0200);
    assertEquals(test.isGap(), false);
    assertEquals(test.isOverlap(), true);
    assertEquals(test.getDateTimeBefore(), before);
    assertEquals(test.getDateTimeAfter(), after);
    assertEquals(test.getInstant(), before.toInstant(OFFSET_0300));
    assertEquals(test.getOffsetBefore(), OFFSET_0300);
    assertEquals(test.getOffsetAfter(), OFFSET_0200);
    assertEquals(test.getDuration(), Duration.of(-1, HOURS));
}
 
Example 34
Project: vertx-acme4j   File: AcmeManager.java   View source code 5 votes vote down vote up
private void schedule() {
    LocalDateTime now = LocalDateTime.now();
    LocalDateTime next = renewalCheckTime.atDate(now.toLocalDate());
    if (next.isBefore(now)) {
        next = next.plusDays(1);
    }
    if (activeTimerId != null) {
        vertx.cancelTimer(activeTimerId);
        activeTimerId = null;
    }
    activeTimerId = vertx.setTimer(now.until(next, MILLIS), timerId -> {
        logger.info("Renewal check starting");
        activeTimerId = null;
        Future<Void> checked;
        try {
            checked = check();
        } catch (IllegalStateException e) {
            // someone else already updating, skip
            checked = failedFuture(e);
        }
        checked.setHandler(ar -> {
            if (ar.succeeded()) {
                logger.info("Renewal check completed successfully");
            } else {
                logger.warn("Renewal check failed", ar.cause());
            }
        });
    });
    logger.info("Scheduled next renewal check at " + next);
}
 
Example 35
Project: OkraSync   File: OkraSyncImpl.java   View source code 5 votes vote down vote up
@Override
public long countDelayed() {
    final Document query = new Document();

    query.put("status", OkraStatus.PENDING.name());
    query.put("runDate", new Document("$lt", DateUtil.toDate(LocalDateTime.now())));

    return client
            .getDatabase(getDatabase())
            .getCollection(getCollection())
            .count(query);
}
 
Example 36
Project: morpheus-core   File: IndexCreateTests.java   View source code 5 votes vote down vote up
@Test()
public void testCreateByClass() {
    Assert.assertEquals(Index.of(Boolean.class, 10).type(), Boolean.class);
    Assert.assertEquals(Index.of(Integer.class, 10).type(), Integer.class);
    Assert.assertEquals(Index.of(Long.class, 10).type(), Long.class);
    Assert.assertEquals(Index.of(Double.class, 10).type(), Double.class);
    Assert.assertEquals(Index.of(String.class, 10).type(), String.class);
    Assert.assertEquals(Index.of(LocalTime.class, 10).type(), LocalTime.class);
    Assert.assertEquals(Index.of(LocalDate.class, 10).type(), LocalDate.class);
    Assert.assertEquals(Index.of(LocalDateTime.class, 10).type(), LocalDateTime.class);
    Assert.assertEquals(Index.of(ZonedDateTime.class, 10).type(), ZonedDateTime.class);
    Assert.assertEquals(Index.of(Year.class, 10).type(), Year.class);
}
 
Example 37
Project: pokeraidbot   File: RaidEntity.java   View source code 5 votes vote down vote up
public boolean existsGroupAt(LocalDateTime startAt) {
    Validate.notNull(startAt, "StartAt");
    for (RaidGroup group : groups) {
        final boolean isMatchingStartTimeIfProvided = group.getStartsAt().equals(startAt);
        if (isMatchingStartTimeIfProvided) {
            return true;
        }
    }
    return false;
}
 
Example 38
Project: jdk8u-jdk   File: TCKOffsetPrinterParser.java   View source code 5 votes vote down vote up
@Test(dataProvider="print_localized")
public void test_print_localized(TextStyle style, LocalDateTime ldt, ZoneOffset offset, String expected) {
    OffsetDateTime odt = OffsetDateTime.of(ldt, offset);
    ZonedDateTime zdt = ldt.atZone(offset);

    DateTimeFormatter f = new DateTimeFormatterBuilder().appendLocalizedOffset(style)
                                                        .toFormatter();
    assertEquals(f.format(odt), expected);
    assertEquals(f.format(zdt), expected);
    assertEquals(f.parse(expected, ZoneOffset::from), offset);

    if (style == TextStyle.FULL) {
        f = new DateTimeFormatterBuilder().appendPattern("ZZZZ")
                                          .toFormatter();
        assertEquals(f.format(odt), expected);
        assertEquals(f.format(zdt), expected);
        assertEquals(f.parse(expected, ZoneOffset::from), offset);

        f = new DateTimeFormatterBuilder().appendPattern("OOOO")
                                          .toFormatter();
        assertEquals(f.format(odt), expected);
        assertEquals(f.format(zdt), expected);
        assertEquals(f.parse(expected, ZoneOffset::from), offset);
    }

    if (style == TextStyle.SHORT) {
        f = new DateTimeFormatterBuilder().appendPattern("O")
                                          .toFormatter();
        assertEquals(f.format(odt), expected);
        assertEquals(f.format(zdt), expected);
        assertEquals(f.parse(expected, ZoneOffset::from), offset);
    }
}
 
Example 39
Project: rs-aggregator   File: ZonedDateTimeUtil.java   View source code 5 votes vote down vote up
public static ZonedDateTime fromXmlString(String value) {
  if (value == null) {
    return null;
  }
  if (value.matches(".*([Z]|[+-][0-9]{1,2}:[0-9]{1,2})$")) {
    return ZonedDateTime.parse(value).withZoneSameInstant(ZoneOffset.UTC);
  } else {
    LocalDateTime local = LocalDateTime.parse(value, localFormat);
    ZonedDateTime localZ = ZonedDateTime.of(local, getZoneId());
    return localZ.withZoneSameInstant(ZoneOffset.UTC);
  }
}
 
Example 40
Project: coodoo-listing   File: DateTest.java   View source code 5 votes vote down vote up
@Ignore
@Test
public void testGernerate() throws IOException {

    LocalDateTime localDateTime1 = LocalDateTime.of(2013, 12, 31, 23, 59, 59);
    LocalDateTime localDateTime2 = LocalDateTime.of(2017, 1, 1, 0, 0, 0);

    LocalDateTime date1 = LocalDateTime.of(2003, 12, 31, 23, 59, 59);
    LocalDateTime date2 = LocalDateTime.of(2007, 1, 1, 0, 0, 0);

    List<String> lines = new ArrayList<>();

    lines.add("<?xml version='1.0' encoding='UTF-8'?>");
    lines.add("<dataset>");

    for (Long id = 1L; id <= 1000; id++) {

        String line = "<TEST_DATES_ENTITY ID='" + id + "'";
        line += " LOCAL_DATE_TIME1='" + localDateTime1.format(DATE_PATTERN) + "'";
        line += " LOCAL_DATE_TIME2='" + localDateTime2.format(DATE_PATTERN) + "'";
        line += " DATE1='" + date1.format(DATE_PATTERN) + "'";
        line += " DATE2='" + date2.format(DATE_PATTERN) + "' />";
        lines.add(line);

        localDateTime1 = localDateTime1.plusDays(1L);
        localDateTime2 = localDateTime2.minusHours(6L);
        date1 = date1.plusDays(1L);
        date2 = date2.minusHours(6L);
    }
    lines.add("</dataset>");

    Path file = Paths.get("src/test/resources/date-dataset.xml");
    Files.write(file, lines, Charset.forName("UTF-8"));
}