Java Code Examples for java.time.LocalDateTime#toInstant()

The following examples show how to use java.time.LocalDateTime#toInstant() . 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: MetricsCollectorTest.java    From syndesis with Apache License 2.0 5 votes vote down vote up
private static RawMetrics raw(String integrationId, String version, String podName, Long messages, String startDateString) {
    DateTimeFormatter formatter = DateTimeFormatter.ofPattern("dd-MM-yyyy HH:mm:ss");
    LocalDateTime localStartDate = LocalDateTime.parse(startDateString, formatter);
    Instant startDate = localStartDate.toInstant(ZoneOffset.UTC);
    return new RawMetrics.Builder()
            .integrationId(integrationId)
            .version(version)
            .pod(podName)
            .messages(messages)
            .errors(1L)
            .startDate(startDate)
            .resetDate(Optional.empty())
            .lastProcessed(Instant.now())
            .build();
}
 
Example 2
Source File: CommitMetadata.java    From javers with Apache License 2.0 5 votes vote down vote up
private Instant initCommitDateInstant(LocalDateTime commitDate, Instant commitDateInstant) {
    if (commitDateInstant != null) {
        return commitDateInstant;
    }

    //for old records without commitDateInstant
    return commitDate.toInstant(ZonedDateTime.now().getOffset());
}
 
Example 3
Source File: AuditRecordController.java    From spring-cloud-dataflow with Apache License 2.0 5 votes vote down vote up
private Instant paresStringToInstant(String textDate) {
	if (textDate == null) {
		return null;
	}

	LocalDateTime localDateTime = LocalDateTime.parse(textDate, DateTimeFormatter.ISO_DATE_TIME);
	return localDateTime.toInstant(ZoneOffset.UTC);
}
 
Example 4
Source File: PersistCase.java    From aws-doc-sdk-examples with Apache License 2.0 5 votes vote down vote up
public void putRecord(String caseId, String employeeName, String email) {

        // Create a DynamoDbClient object
        Region region = Region.US_WEST_2;
        DynamoDbClient ddb = DynamoDbClient.builder()
                .region(region)
                .build();

        // Create a DynamoDbEnhancedClient and use the DynamoDbClient object
        DynamoDbEnhancedClient enhancedClient = DynamoDbEnhancedClient.builder()
                .dynamoDbClient(ddb)
                .build();


        try {
            // Create a DynamoDbTable object
            DynamoDbTable<Case> caseTable = enhancedClient.table("Case", TableSchema.fromBean(Case.class));

            // Create an Instat object
            LocalDate localDate = LocalDate.parse("2020-04-07");
            LocalDateTime localDateTime = localDate.atStartOfDay();
            Instant instant = localDateTime.toInstant(ZoneOffset.UTC);

            // Populate the table
            Case caseRecord = new Case();
            caseRecord.setName(employeeName);
            caseRecord.setId(caseId);
            caseRecord.setEmail(email);
            caseRecord.setRegistrationDate(instant) ;

            // Put the case data into a DynamoDB table
            caseTable.putItem(caseRecord);

        } catch (DynamoDbException e) {
            System.err.println(e.getMessage());
            System.exit(1);
        }
        System.out.println("done");
    }
 
Example 5
Source File: EnhancedPutItem.java    From aws-doc-sdk-examples with Apache License 2.0 5 votes vote down vote up
public static void putRecord(DynamoDbEnhancedClient enhancedClient) {

        try {
            // Create a DynamoDbTable object
            DynamoDbTable<Customer> custTable = enhancedClient.table("Customer", TableSchema.fromBean(Customer.class));

            // Create an Instant object
            LocalDate localDate = LocalDate.parse("2020-04-07");
            LocalDateTime localDateTime = localDate.atStartOfDay();
            Instant instant = localDateTime.toInstant(ZoneOffset.UTC);

            // Populate the table
            Customer custRecord = new Customer();
            custRecord.setCustName("Susan Blue");
            custRecord.setId("id103");
            custRecord.setEmail("[email protected]");
            custRecord.setRegistrationDate(instant) ;

            // Put the customer data into a DynamoDB table
            custTable.putItem(custRecord);

        } catch (DynamoDbException e) {
            System.err.println(e.getMessage());
            System.exit(1);
        }
        System.out.println("done");
    }
 
Example 6
Source File: DynamoDbBeanExample.java    From aws-doc-sdk-examples with Apache License 2.0 5 votes vote down vote up
public static void putRecord(DynamoDbEnhancedClient enhancedClient) {

        try {
            //Create a DynamoDbTable object
            DynamoDbTable<Customer> custTable = enhancedClient.table("Customer", TableSchema.fromBean(Customer.class));

            //Create am Instat
            LocalDate localDate = LocalDate.parse("2020-04-07");
            LocalDateTime localDateTime = localDate.atStartOfDay();
            Instant instant = localDateTime.toInstant(ZoneOffset.UTC);

            //Populate the Table
            Customer custRecord = new Customer();
            custRecord.setCustName("Susan Blue");
            custRecord.setId("id103");
            custRecord.setEmail("[email protected]");
            custRecord.setRegistrationDate(instant) ;

            //Put the customer data into a DynamoDB table
            custTable.putItem(custRecord);

        } catch (DynamoDbException e) {
            System.err.println(e.getMessage());
            System.exit(1);
        }
        System.out.println("done");
    }
 
Example 7
Source File: SerializerH3LocalDateTime.java    From baratine with GNU General Public License v2.0 5 votes vote down vote up
@Override
public void writeObject(OutRawH3 os, int defId, LocalDateTime time, OutH3 out)
{
  os.writeObject(typeSequence());

  Instant instant = time.toInstant(ZoneOffset.UTC);

  os.writeLong(instant.getEpochSecond());
  os.writeLong(instant.getNano());
}
 
Example 8
Source File: InstantCodec.java    From r2dbc-mysql with Apache License 2.0 5 votes vote down vote up
@Override
public Instant decode(ByteBuf value, FieldInformation info, Class<?> target, boolean binary, CodecContext context) {
    LocalDateTime origin = LocalDateTimeCodec.decodeOrigin(value, binary, context);

    if (origin == null) {
        return null;
    }

    return origin.toInstant(context.getServerZoneId().getRules().getOffset(origin));
}
 
Example 9
Source File: DateUtils.java    From Raincat with GNU Lesser General Public License v3.0 5 votes vote down vote up
/**
 * 将当前时区时间转成UTC时间.
 *
 * @param dateTime 时间
 * @return LocalDateTime local date time
 */
public static LocalDateTime toUTCDateTime(final LocalDateTime dateTime) {
    if (dateTime == null) {
        return null;
    } else {
        Instant instant = dateTime.toInstant(DEFAULT_ZONE.getRules().getOffset(dateTime));
        return LocalDateTime.ofEpochSecond(instant.getEpochSecond(), instant.getNano(), ZoneOffset.UTC);
    }
}
 
Example 10
Source File: DateUtilTest.java    From spring-batch-rest with Apache License 2.0 5 votes vote down vote up
@Test
public void testLocalDateConversion() {
	Date now = new Date();
	LocalDateTime localDateTime = DateUtil.localDateTime(now);
	Instant ldtInstant = localDateTime.toInstant(OffsetDateTime.now().getOffset());

	Assertions.assertEquals(ldtInstant, now.toInstant());
}
 
Example 11
Source File: InstantIdentityFactoryTestCase.java    From jstarcraft-core with Apache License 2.0 5 votes vote down vote up
@Override
protected IdentityFactory getIdentityFactory() {
    IdentityDefinition definition = new IdentityDefinition(5, 40, 18);
    LocalDateTime dateTime = LocalDateTime.of(2017, 1, 1, 0, 0, 0);
    Instant instant = dateTime.toInstant(ZoneOffset.UTC);
    InstantIdentityFactory identityFactory = new InstantIdentityFactory(definition, 0, instant);
    return identityFactory;
}
 
Example 12
Source File: InstantCodec.java    From r2dbc-mysql with Apache License 2.0 5 votes vote down vote up
@Override
public Instant decode(ByteBuf value, FieldInformation info, Class<?> target, boolean binary, CodecContext context) {
    LocalDateTime origin = LocalDateTimeCodec.decodeOrigin(value, binary, context);

    if (origin == null) {
        return null;
    }

    return origin.toInstant(context.getServerZoneId().getRules().getOffset(origin));
}
 
Example 13
Source File: TestKata2LocalAndZonedDateTimes.java    From java-katas with MIT License 5 votes vote down vote up
@Test
@Tag("TODO")
@Order(9)
public void verifyZonedDateTimeUsingClock() {

    // *****************************************************
    // Demonstrate creating a new ZonedDateTime if GMT +1
    // from the clock now(). Convert a LocalDateTime into
    // an Instant, which can subsequently be used to
    // create the new ZonedDateTime
    // *****************************************************

    LocalDateTime theOriginalJudgementDayDateTime =
            LocalDateTime.now(terminatorOriginalJudgementDay);

    Instant tojdInstant = theOriginalJudgementDayDateTime
            .toInstant(ZoneOffset.of("+0000"));

    // TODO: Replace ZonedDateTime.now() to get date time in GMT +1 offset.
    //  Given a timestamp of 1997-08-29T07:14:30Z,
    //  fix it to display in GMT +1. Show the same Instant in a different zone.
    //  Check: java.time.ZonedDateTime.ofInstant(java.time.Instant, java.time.ZoneId)
    ZonedDateTime gmtPlusOneHourTimeForTOJD =
            ZonedDateTime.now();

    assertEquals(8,
            gmtPlusOneHourTimeForTOJD.getMonthValue(),
            "The expected and actual month values should match");

    assertEquals(3,
            gmtPlusOneHourTimeForTOJD.getHour(),
            "The expected and actual hour values should match");

    assertEquals(Integer.valueOf(14),
            gmtPlusOneHourTimeForTOJD.getMinute(),
            "The expected and actual minute values should match");
}
 
Example 14
Source File: TestSolution2LocalAndZonedDateTimes.java    From java-katas with MIT License 5 votes vote down vote up
@Test
@Tag("PASSING")
@Order(9)
public void verifyZonedDateTimeUsingClock() {

    // *****************************************************
    // Demonstrate creating a new ZonedDateTime if GMT +1
    // from the clock now(). Convert a LocalDateTime into
    // an Instant, which can subsequently be used to
    // create the new ZonedDateTime
    // *****************************************************

    LocalDateTime theOriginalJudgementDayDateTime =
            LocalDateTime.now(terminatorOriginalJudgementDay);

    Instant tojdInstant = theOriginalJudgementDayDateTime
            .toInstant(ZoneOffset.of("+0000"));

    // DONE: Replace ZonedDateTime.now() to get date time in GMT +1 offset.
    //  Given a timestamp of 1997-08-29T07:14:30Z,
    //  fix it to display in GMT +1. Show the same Instant in a different zone.
    //  Check: java.time.ZonedDateTime.ofInstant(java.time.Instant, java.time.ZoneId)
    ZonedDateTime gmtPlusOneHourTimeForTOJD =
            ZonedDateTime.ofInstant(tojdInstant, ZoneId.of("GMT+1"));

    assertEquals(8,
            gmtPlusOneHourTimeForTOJD.getMonthValue(),
            "The expected and actual month values should match");

    assertEquals(3,
            gmtPlusOneHourTimeForTOJD.getHour(),
            "The expected and actual hour values should match");

    assertEquals(Integer.valueOf(14),
            gmtPlusOneHourTimeForTOJD.getMinute(),
            "The expected and actual minute values should match");
}
 
Example 15
Source File: ParseDateFieldUpdateProcessorFactory.java    From lucene-solr with Apache License 2.0 4 votes vote down vote up
private static Instant parseInstant(DateTimeFormatter formatter, String dateStr, ParsePosition parsePosition) {
  // prepare for reuse
  parsePosition.setIndex(0);
  parsePosition.setErrorIndex(-1);
  final TemporalAccessor temporal = formatter.parse(dateStr, parsePosition);
  // check that all content has been parsed
  if (parsePosition.getIndex() < dateStr.length()) {
    final String abbr;
    if (dateStr.length() > 64) {
      abbr = dateStr.subSequence(0, 64).toString() + "...";
    } else {
      abbr = dateStr;
    }
    throw new DateTimeParseException("Text '" + abbr + "' could not be parsed, unparsed text found at index " +
        parsePosition.getIndex(), dateStr, parsePosition.getIndex());
  }

  // Get Date; mandatory
  LocalDate date = temporal.query(TemporalQueries.localDate());//mandatory
  if (date == null) {
    throw new SolrException(SolrException.ErrorCode.SERVER_ERROR,
        "Date (year, month, day) is mandatory: " + formatter.toFormat().toString());
  }
  // Get Time; optional
  LocalTime time = temporal.query(TemporalQueries.localTime());
  if (time == null) {
    time = LocalTime.MIN;
  }

  final LocalDateTime localDateTime = LocalDateTime.of(date, time);

  // Get Zone Offset; optional
  ZoneOffset offset = temporal.query(TemporalQueries.offset());
  if (offset == null) {
    // no Zone offset; get Zone ID
    ZoneId zoneId = temporal.query(TemporalQueries.zone());
    if (zoneId == null) {
      zoneId = formatter.getZone();
      if (zoneId == null) {
        zoneId = ZoneOffset.UTC;
      }
    }
    return localDateTime.atZone(zoneId).toInstant();
  } else {
    return localDateTime.toInstant(offset);
  }
}
 
Example 16
Source File: TimeZoneIntegrationTestSupport.java    From r2dbc-mysql with Apache License 2.0 4 votes vote down vote up
private static Instant toInstant(LocalDateTime value) {
    return value.toInstant(ZoneId.systemDefault().getRules().getOffset(value));
}
 
Example 17
Source File: EnhancedBatchWriteItems.java    From aws-doc-sdk-examples with Apache License 2.0 4 votes vote down vote up
public static void putBatchRecords(DynamoDbEnhancedClient enhancedClient) {
    try {

        // Create a DynamoDbTable object
        DynamoDbTable<Customer> mappedTable = enhancedClient.table("Customer", TableSchema.fromBean(Customer.class));

        // Create an Instant object
        LocalDate localDate = LocalDate.parse("2020-04-07");
        LocalDateTime localDateTime = localDate.atStartOfDay();
        Instant instant = localDateTime.toInstant(ZoneOffset.UTC);

        // Populate the table
        Customer record2 = new Customer();
        record2.setCustName("Fred Pink");
        record2.setId("id110");
        record2.setEmail("[email protected]");
        record2.setRegistrationDate(instant) ;

        Customer record3 = new Customer();
        record3.setCustName("Susan Pink");
        record3.setId("id120");
        record3.setEmail("[email protected]");
        record3.setRegistrationDate(instant) ;

        // Create a BatchWriteItemEnhancedRequest object
        BatchWriteItemEnhancedRequest batchWriteItemEnhancedRequest =
                BatchWriteItemEnhancedRequest.builder()
                        .writeBatches(
                                WriteBatch.builder(Customer.class)
                                        .mappedTableResource(mappedTable)
                                        .addPutItem(r -> r.item(record2))
                                        .addPutItem(r -> r.item(record3))
                                        .build())
                        .build();

        // Add these two items to the table
        enhancedClient.batchWriteItem(batchWriteItemEnhancedRequest);
        System.out.println("done");

    } catch (DynamoDbException e) {
        System.err.println(e.getMessage());
        System.exit(1);
    }
}
 
Example 18
Source File: TimeZoneIntegrationTestSupport.java    From r2dbc-mysql with Apache License 2.0 4 votes vote down vote up
private static Instant toInstant(LocalDateTime value) {
    return value.toInstant(ZoneId.systemDefault().getRules().getOffset(value));
}
 
Example 19
Source File: DateUtils.java    From dhis2-core with BSD 3-Clause "New" or "Revised" License 3 votes vote down vote up
/**
 * Creates a {@link java.util.Date} from the given {@link java.time.LocalDateTime}
 * based on the UTC time zone.
 *
 * @param time the LocalDateTime.
 * @return a Date.
 */
public static Date getDate( LocalDateTime time )
{
    Instant instant = time.toInstant( ZoneOffset.UTC );

    return Date.from( instant );
}