Example usage for java.util Date toInstant

List of usage examples for java.util Date toInstant

Introduction

In this page you can find the example usage for java.util Date toInstant.

Prototype

public Instant toInstant() 

Source Link

Document

Converts this Date object to an Instant .

Usage

From source file:com.fantasy.stataggregator.workers.GameDataRetrieverTask.java

/**
 * Determines if a game has already been played, No current game data<br>
 * will be pulled, since the statistics aren't final.
 *
 * @param sched/*w  ww.j  av  a2s  .  c o m*/
 * @return
 */
private boolean hasBeenPlayed(GameSchedule sched) throws ParseException {
    Date gameDate = sched.getGamedate();
    if (Objects.nonNull(gameDate)) {
        LocalDate dateOnly = LocalDateTime.ofInstant(gameDate.toInstant(), ZoneId.systemDefault())
                .toLocalDate();

        return dateOnly.isBefore(LocalDate.now());
    }
    return false;
}

From source file:org.apache.solr.client.solrj.io.stream.eval.TemporalEvaluatorsTest.java

@Test
public void testFunctionsOnInstant() throws Exception {
    Calendar calendar = new GregorianCalendar(TimeZone.getTimeZone("UTC"), Locale.ROOT);
    calendar.set(2017, 12, 5, 23, 59);/*from w  w  w  .  ja v  a2s  .c  o m*/
    Date aDate = calendar.getTime();
    Instant instant = aDate.toInstant();
    testFunction("year(a)", instant, calendar.get(Calendar.YEAR));
    testFunction("month(a)", instant, calendar.get(Calendar.MONTH) + 1);
    testFunction("day(a)", instant, calendar.get(Calendar.DAY_OF_MONTH));
    testFunction("hour(a)", instant, calendar.get(Calendar.HOUR_OF_DAY));
    testFunction("minute(a)", instant, calendar.get(Calendar.MINUTE));
    testFunction("epoch(a)", instant, aDate.getTime());
}

From source file:org.openhab.binding.nest.handler.NestBaseHandler.java

protected State getAsDateTimeTypeOrNull(@Nullable Date date) {
    if (date == null) {
        return UnDefType.NULL;
    }/*w  w w.j a v a  2s  . c o  m*/

    long offsetMillis = TimeZone.getDefault().getOffset(date.getTime());
    Instant instant = date.toInstant().plusMillis(offsetMillis);
    return new DateTimeType(ZonedDateTime.ofInstant(instant, TimeZone.getDefault().toZoneId()));
}

From source file:com.buffalokiwi.api.APIDate.java

/**
 * Create a new APIDate using the local system offset 
 * @param date date to use //from   w  w w  . jav  a 2 s.  c om
 */
public APIDate(final Date date) {
    if (date == null)
        throw new IllegalArgumentException("date can't be null");

    this.date = date.toInstant().atZone(ZoneId.systemDefault());
    offset = ZoneId.systemDefault().getRules().getOffset(date.toInstant());
}

From source file:am.ik.categolj3.api.git.GitStore.java

Author author(RevCommit commit) {
    String name = commit != null ? commit.getAuthorIdent().getName() : "";
    Date date = commit != null ? commit.getAuthorIdent().getWhen() : new Date();
    OffsetDateTime o = OffsetDateTime.ofInstant(date.toInstant(), ZoneId.systemDefault());
    return new Author(name, o);
}

From source file:com.esri.geoportal.harvester.agp.AgpOutputBroker.java

private String fromatDate(Date date) {
    ZonedDateTime zonedDateTime = ZonedDateTime.ofInstant(date.toInstant(), ZoneId.systemDefault());
    return FORMATTER.format(zonedDateTime);
}

From source file:com.netflix.metacat.connector.hive.converters.HiveConnectorInfoConverter.java

@VisibleForTesting
Integer dateToEpochSeconds(final Date date) {
    return null == date ? null : Math.toIntExact(date.toInstant().getEpochSecond());
}

From source file:jef.tools.DateUtils.java

/**
 * Convert to Instance/*from  www.j a v a  2 s.co m*/
 * 
 * @see Instant
 * @param date
 *            java.util.Date
 * @return instant
 */
public static Instant toInstant(Date date) {
    return date == null ? null : date.toInstant();
}

From source file:org.dhatim.fastexcel.Correctness.java

@Test
public void singleWorksheet() throws Exception {
    String sheetName = "Worksheet 1";
    String stringValue = "Sample text with chars to escape : < > & \\ \" ' ~        ";
    Date dateValue = new Date();
    LocalDateTime localDateTimeValue = LocalDateTime.now();
    ZoneId timezone = ZoneId.of("Australia/Sydney");
    ZonedDateTime zonedDateValue = ZonedDateTime.ofInstant(dateValue.toInstant(), timezone);
    double doubleValue = 1.234;
    int intValue = 2_016;
    long longValue = 2_016_000_000_000L;
    BigDecimal bigDecimalValue = BigDecimal.TEN;
    byte[] data = writeWorkbook(wb -> {
        Worksheet ws = wb.newWorksheet(sheetName);
        int i = 1;
        ws.value(i, i++, stringValue);/*  ww w.  j  av  a2  s . c  om*/
        ws.value(i, i++, dateValue);
        ws.value(i, i++, localDateTimeValue);
        ws.value(i, i++, zonedDateValue);
        ws.value(i, i++, doubleValue);
        ws.value(i, i++, intValue);
        ws.value(i, i++, longValue);
        ws.value(i, i++, bigDecimalValue);
        try {
            ws.finish();
        } catch (IOException ex) {
            throw new RuntimeException(ex);
        }
    });

    // Check generated workbook with Apache POI
    XSSFWorkbook xwb = new XSSFWorkbook(new ByteArrayInputStream(data));
    assertThat(xwb.getActiveSheetIndex()).isEqualTo(0);
    assertThat(xwb.getNumberOfSheets()).isEqualTo(1);
    XSSFSheet xws = xwb.getSheet(sheetName);
    @SuppressWarnings("unchecked")
    Comparable<XSSFRow> row = (Comparable) xws.getRow(0);
    assertThat(row).isNull();
    int i = 1;
    assertThat(xws.getRow(i).getCell(i++).getStringCellValue()).isEqualTo(stringValue);
    assertThat(xws.getRow(i).getCell(i++).getDateCellValue()).isEqualTo(dateValue);
    // Check zoned timestamps have the same textual representation as the Dates extracted from the workbook
    // (Excel date serial numbers do not carry timezone information)
    assertThat(DateTimeFormatter.ISO_LOCAL_DATE_TIME.format(ZonedDateTime
            .ofInstant(xws.getRow(i).getCell(i++).getDateCellValue().toInstant(), ZoneId.systemDefault())))
                    .isEqualTo(DateTimeFormatter.ISO_LOCAL_DATE_TIME.format(localDateTimeValue));
    assertThat(DateTimeFormatter.ISO_LOCAL_DATE_TIME.format(ZonedDateTime
            .ofInstant(xws.getRow(i).getCell(i++).getDateCellValue().toInstant(), ZoneId.systemDefault())))
                    .isEqualTo(DateTimeFormatter.ISO_LOCAL_DATE_TIME.format(zonedDateValue));
    assertThat(xws.getRow(i).getCell(i++).getNumericCellValue()).isEqualTo(doubleValue);
    assertThat(xws.getRow(i).getCell(i++).getNumericCellValue()).isEqualTo(intValue);
    assertThat(xws.getRow(i).getCell(i++).getNumericCellValue()).isEqualTo(longValue);
    assertThat(new BigDecimal(xws.getRow(i).getCell(i++).getRawValue())).isEqualTo(bigDecimalValue);
}

From source file:org.apache.solr.cloud.CreateRoutedAliasTest.java

@Test
public void testV2() throws Exception {
    // note we don't use TZ in this test, thus it's UTC
    final String aliasName = getTestName();

    String createNode = cluster.getRandomJetty(random()).getNodeName();

    final String baseUrl = cluster.getRandomJetty(random()).getBaseUrl().toString();
    //TODO fix Solr test infra so that this /____v2/ becomes /api/
    HttpPost post = new HttpPost(baseUrl + "/____v2/c");
    post.setEntity(new StringEntity("{\n" + "  \"create-alias\" : {\n" + "    \"name\": \"" + aliasName
            + "\",\n" + "    \"router\" : {\n" + "      \"name\": \"time\",\n"
            + "      \"field\": \"evt_dt\",\n" + "      \"start\":\"NOW/DAY\",\n" + // small window for test failure once a day.
            "      \"interval\":\"+2HOUR\",\n" + "      \"maxFutureMs\":\"14400000\"\n" + "    },\n" +
            //TODO should we use "NOW=" param?  Won't work with v2 and is kinda a hack any way since intended for distrib
            "    \"create-collection\" : {\n" + "      \"router\": {\n" + "        \"name\":\"implicit\",\n"
            + "        \"field\":\"foo_s\"\n" + "      },\n" + "      \"shards\":\"foo,bar\",\n"
            + "      \"config\":\"_default\",\n" + "      \"tlogReplicas\":1,\n" + "      \"pullReplicas\":1,\n"
            + "      \"maxShardsPerNode\":4,\n" + // note: we also expect the 'policy' to work fine
            "      \"nodeSet\": ['" + createNode + "'],\n" + "      \"properties\" : {\n"
            + "        \"foobar\":\"bazbam\",\n" + "        \"foobar2\":\"bazbam2\"\n" + "      }\n" + "    }\n"
            + "  }\n" + "}", ContentType.APPLICATION_JSON));
    assertSuccess(post);//from w  w  w . j  a v  a  2  s  .co m

    Date startDate = DateMathParser.parseMath(new Date(), "NOW/DAY");
    String initialCollectionName = TimeRoutedAlias.formatCollectionNameFromInstant(aliasName,
            startDate.toInstant());
    // small chance could fail due to "NOW"; see above
    assertCollectionExists(initialCollectionName);

    // Test created collection:
    final DocCollection coll = solrClient.getClusterStateProvider().getState(initialCollectionName).get();
    //System.err.println(coll);
    //TODO how do we assert the configSet ?
    assertEquals(ImplicitDocRouter.class, coll.getRouter().getClass());
    assertEquals("foo_s", ((Map) coll.get("router")).get("field"));
    assertEquals(2, coll.getSlices().size()); // numShards
    assertEquals(4, coll.getSlices().stream().mapToInt(s -> s.getReplicas().size()).sum()); // num replicas
    // we didn't ask for any NRT replicas
    assertEquals(0, coll.getSlices().stream()
            .mapToInt(s -> s.getReplicas(r -> r.getType() == Replica.Type.NRT).size()).sum());
    //assertEquals(1, coll.getNumNrtReplicas().intValue()); // TODO seems to be erroneous; I figured 'null'
    assertEquals(1, coll.getNumTlogReplicas().intValue()); // per-shard
    assertEquals(1, coll.getNumPullReplicas().intValue()); // per-shard
    assertEquals(4, coll.getMaxShardsPerNode());
    //TODO SOLR-11877 assertEquals(2, coll.getStateFormat());
    assertTrue("nodeSet didn't work?", coll.getSlices().stream().flatMap(s -> s.getReplicas().stream())
            .map(Replica::getNodeName).allMatch(createNode::equals));

    // Test Alias metadata:
    Aliases aliases = cluster.getSolrClient().getZkStateReader().getAliases();
    Map<String, String> collectionAliasMap = aliases.getCollectionAliasMap();
    assertEquals(initialCollectionName, collectionAliasMap.get(aliasName));
    Map<String, String> meta = aliases.getCollectionAliasProperties(aliasName);
    //System.err.println(new TreeMap(meta));
    assertEquals("evt_dt", meta.get("router.field"));
    assertEquals("_default", meta.get("create-collection.collection.configName"));
    assertEquals("foo_s", meta.get("create-collection.router.field"));
    assertEquals("bazbam", meta.get("create-collection.property.foobar"));
    assertEquals("bazbam2", meta.get("create-collection.property.foobar2"));
    assertEquals(createNode, meta.get("create-collection.createNodeSet"));
}