org.threeten.bp.LocalDateTime Java Examples

The following examples show how to use org.threeten.bp.LocalDateTime. 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: SpannerSample.java    From java-docs-samples with Apache License 2.0 6 votes vote down vote up
static void updateBackup(DatabaseAdminClient dbAdminClient, BackupId backupId) {
  // Get current backup metadata.
  Backup backup = dbAdminClient.newBackupBuilder(backupId).build().reload();
  // Add 30 days to the expire time.
  // Expire time must be within 366 days of the create time of the backup.
  Timestamp expireTime =
      Timestamp.ofTimeMicroseconds(
          TimeUnit.SECONDS.toMicros(backup.getExpireTime().getSeconds())
              + TimeUnit.NANOSECONDS.toMicros(backup.getExpireTime().getNanos())
              + TimeUnit.DAYS.toMicros(30L));
  System.out.println(String.format(
      "Updating expire time of backup [%s] to %s...",
      backupId.toString(),
      LocalDateTime.ofEpochSecond(
          expireTime.getSeconds(),
          expireTime.getNanos(),
          OffsetDateTime.now().getOffset()).toString()));

  // Update expire time.
  backup = backup.toBuilder().setExpireTime(expireTime).build();
  backup.updateExpireTime();
  System.out.println("Updated backup [" + backupId + "]");
}
 
Example #2
Source File: TestStandardZoneRules.java    From threetenbp with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
public void test_Dublin_getOffsetInfo_overlap() {
    ZoneRules test = europeDublin();
    final LocalDateTime dateTime = LocalDateTime.of(2008, 10, 26, 1, 0, 0, 0);
    ZoneOffsetTransition trans = checkOffset(test, dateTime, OFFSET_PONE, OVERLAP);
    assertEquals(trans.isGap(), false);
    assertEquals(trans.isOverlap(), true);
    assertEquals(trans.getOffsetBefore(), OFFSET_PONE);
    assertEquals(trans.getOffsetAfter(), OFFSET_ZERO);
    assertEquals(trans.getInstant(), createInstant(2008, 10, 26, 1, 0, ZoneOffset.UTC));
    assertEquals(trans.getDateTimeBefore(), LocalDateTime.of(2008, 10, 26, 2, 0));
    assertEquals(trans.getDateTimeAfter(), LocalDateTime.of(2008, 10, 26, 1, 0));
    assertEquals(trans.isValidOffset(ZoneOffset.ofHours(-1)), false);
    assertEquals(trans.isValidOffset(OFFSET_ZERO), true);
    assertEquals(trans.isValidOffset(OFFSET_PONE), true);
    assertEquals(trans.isValidOffset(OFFSET_PTWO), false);
    assertEquals(trans.toString(), "Transition[Overlap at 2008-10-26T02:00+01:00 to Z]");
}
 
Example #3
Source File: StandardZoneRules.java    From threetenbp with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
/**
 * Finds the offset info for a local date-time and transition.
 *
 * @param dt  the date-time, not null
 * @param trans  the transition, not null
 * @return the offset info, not null
 */
private Object findOffsetInfo(LocalDateTime dt, ZoneOffsetTransition trans) {
    LocalDateTime localTransition = trans.getDateTimeBefore();
    if (trans.isGap()) {
        if (dt.isBefore(localTransition)) {
            return trans.getOffsetBefore();
        }
        if (dt.isBefore(trans.getDateTimeAfter())) {
            return trans;
        } else {
            return trans.getOffsetAfter();
        }
    } else {
        if (dt.isBefore(localTransition) == false) {
            return trans.getOffsetAfter();
        }
        if (dt.isBefore(trans.getDateTimeAfter())) {
            return trans.getOffsetBefore();
        } else {
            return trans;
        }
    }
}
 
Example #4
Source File: TestStandardZoneRules.java    From threetenbp with BSD 3-Clause "New" or "Revised" License 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 #5
Source File: TestStandardZoneRules.java    From threetenbp with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
public void test_Paris_getOffsetInfo_overlap() {
    ZoneRules test = europeParis();
    final LocalDateTime dateTime = LocalDateTime.of(2008, 10, 26, 2, 0, 0, 0);
    ZoneOffsetTransition trans = checkOffset(test, dateTime, OFFSET_PTWO, OVERLAP);
    assertEquals(trans.isGap(), false);
    assertEquals(trans.isOverlap(), true);
    assertEquals(trans.getOffsetBefore(), OFFSET_PTWO);
    assertEquals(trans.getOffsetAfter(), OFFSET_PONE);
    assertEquals(trans.getInstant(), createInstant(2008, 10, 26, 1, 0, ZoneOffset.UTC));
    assertEquals(trans.isValidOffset(OFFSET_ZERO), false);
    assertEquals(trans.isValidOffset(OFFSET_PONE), true);
    assertEquals(trans.isValidOffset(OFFSET_PTWO), true);
    assertEquals(trans.isValidOffset(ZoneOffset.ofHours(3)), false);
    assertEquals(trans.toString(), "Transition[Overlap at 2008-10-26T03:00+02:00 to +01:00]");

    assertFalse(trans.equals(null));
    assertFalse(trans.equals(OFFSET_PTWO));
    assertTrue(trans.equals(trans));

    final ZoneOffsetTransition otherTrans = test.getTransition(dateTime);
    assertTrue(trans.equals(otherTrans));
    assertEquals(trans.hashCode(), otherTrans.hashCode());
}
 
Example #6
Source File: TestDateTimeTextPrinting.java    From threetenbp with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
@Test
public void test_appendTextMap() throws Exception {
    Map<Long, String> map = new HashMap<Long, String>();
    map.put(1L, "JNY");
    map.put(2L, "FBY");
    map.put(3L, "MCH");
    map.put(4L, "APL");
    map.put(5L, "MAY");
    map.put(6L, "JUN");
    map.put(7L, "JLY");
    map.put(8L, "AGT");
    map.put(9L, "SPT");
    map.put(10L, "OBR");
    map.put(11L, "NVR");
    map.put(12L, "DBR");
    builder.appendText(MONTH_OF_YEAR, map);
    DateTimeFormatter f = builder.toFormatter();
    LocalDateTime dt = LocalDateTime.of(2010, 1, 1, 0, 0);
    for (Month month : Month.values()) {
        assertEquals(f.format(dt.with(month)), map.get((long) month.getValue()));
    }
}
 
Example #7
Source File: TestZoneOffsetTransition.java    From threetenbp with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
@Test
public void test_equals() {
    LocalDateTime ldtA = LocalDateTime.of(2010, 3, 31, 1, 0);
    ZoneOffsetTransition a1 = ZoneOffsetTransition.of(ldtA, OFFSET_0200, OFFSET_0300);
    ZoneOffsetTransition a2 = ZoneOffsetTransition.of(ldtA, OFFSET_0200, OFFSET_0300);
    LocalDateTime ldtB = LocalDateTime.of(2010, 10, 31, 1, 0);
    ZoneOffsetTransition b = ZoneOffsetTransition.of(ldtB, OFFSET_0300, OFFSET_0200);

    assertEquals(a1.equals(a1), true);
    assertEquals(a1.equals(a2), true);
    assertEquals(a1.equals(b), false);
    assertEquals(a2.equals(a1), true);
    assertEquals(a2.equals(a2), true);
    assertEquals(a2.equals(b), false);
    assertEquals(b.equals(a1), false);
    assertEquals(b.equals(a2), false);
    assertEquals(b.equals(b), true);

    assertEquals(a1.equals(""), false);
    assertEquals(a1.equals(null), false);
}
 
Example #8
Source File: Session.java    From droidconat-2016 with Apache License 2.0 5 votes vote down vote up
protected Session(Parcel in) {
    id = in.readInt();
    room = in.readString();
    speakers = in.createTypedArrayList(Speaker.CREATOR);
    title = in.readString();
    description = in.readString();
    fromTime = (LocalDateTime) in.readSerializable();
    toTime = (LocalDateTime) in.readSerializable();
}
 
Example #9
Source File: AppMapper.java    From droidconat-2016 with Apache License 2.0 5 votes vote down vote up
private List<ScheduleSlot> mapToScheduleSlots(@NonNull List<Session> sortedSessions) {
    List<ScheduleSlot> slots = new ArrayList<>();

    LocalDateTime previousTime = null;
    List<Session> previousSessionsList = null;

    LocalDateTime currentTime;
    for (Session currentSession : sortedSessions) {
        currentTime = currentSession.getFromTime();
        if (previousSessionsList != null) {
            if (currentTime.equals(previousTime)) {
                previousSessionsList.add(currentSession);
            } else {
                slots.add(new ScheduleSlot(previousTime, sortPerRoomId(previousSessionsList)));
                previousSessionsList = null;
            }
        }

        if (previousSessionsList == null) {
            previousTime = currentTime;
            previousSessionsList = new ArrayList<>();
            previousSessionsList.add(currentSession);
        }
    }

    if (previousSessionsList != null) {
        slots.add(new ScheduleSlot(previousTime, sortPerRoomId(previousSessionsList)));
    }
    return slots;
}
 
Example #10
Source File: ScheduleDayEntry.java    From droidconat-2016 with Apache License 2.0 5 votes vote down vote up
private String formatSessionTime(Session session) {
    LocalDateTime fromTime = session.getFromTime();
    LocalDateTime toTime = session.getToTime();
    long minutes = ChronoUnit.MINUTES.between(fromTime, toTime);
    return itemView.getContext().getString(R.string.schedule_day_entry_session_time_format,
            formatTime(fromTime), formatTime(toTime), minutes);
}
 
Example #11
Source File: ScheduleDayFragmentAdapterMySessions.java    From droidconat-2016 with Apache License 2.0 5 votes vote down vote up
private Session findSelectedSession(LocalDateTime slotTime, List<Session> slotSessions) {
    Integer selectedSessionId = selectedSessionsMemory.get(slotTime);
    if (selectedSessionId == null) {
        return null;
    }

    return stream(slotSessions)
            .filter(session -> session.getId() == selectedSessionId)
            .findFirst().orElse(null);
}
 
Example #12
Source File: TestDateTimeTextPrinting.java    From threetenbp with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
@Test
public void test_print_appendText2arg_french_short() throws Exception {
    DateTimeFormatter f = builder.appendText(MONTH_OF_YEAR, TextStyle.SHORT).toFormatter(Locale.FRENCH);
    LocalDateTime dt = LocalDateTime.of(2010, 1, 1, 0, 0);
    String text = f.format(dt);
    assertEquals(text, "janv.");
}
 
Example #13
Source File: RemoteAttestationCipher.java    From mollyim-android with GNU General Public License v3.0 5 votes vote down vote up
public static void verifyIasSignature(KeyStore trustStore, String certificates, String signatureBody, String signature, Quote quote)
    throws SignatureException
{
  if (certificates == null || certificates.isEmpty()) {
    throw new SignatureException("No certificates.");
  }

  try {
    SigningCertificate signingCertificate = new SigningCertificate(certificates, trustStore);
    signingCertificate.verifySignature(signatureBody, signature);

    SignatureBodyEntity signatureBodyEntity = JsonUtil.fromJson(signatureBody, SignatureBodyEntity.class);

    if (signatureBodyEntity.getVersion() != SIGNATURE_BODY_VERSION) {
      throw new SignatureException("Unexpected signed quote version " + signatureBodyEntity.getVersion());
    }

    if (!MessageDigest.isEqual(ByteUtil.trim(signatureBodyEntity.getIsvEnclaveQuoteBody(), 432), ByteUtil.trim(quote.getQuoteBytes(), 432))) {
      throw new SignatureException("Signed quote is not the same as RA quote: " + Hex.toStringCondensed(signatureBodyEntity.getIsvEnclaveQuoteBody()) + " vs " + Hex.toStringCondensed(quote.getQuoteBytes()));
    }

    if (!"OK".equals(signatureBodyEntity.getIsvEnclaveQuoteStatus())) {
      throw new SignatureException("Quote status is: " + signatureBodyEntity.getIsvEnclaveQuoteStatus());
    }

    if (Instant.from(ZonedDateTime.of(LocalDateTime.from(DateTimeFormatter.ofPattern("yyy-MM-dd'T'HH:mm:ss.SSSSSS").parse(signatureBodyEntity.getTimestamp())), ZoneId.of("UTC")))
               .plus(Period.ofDays(1))
               .isBefore(Instant.now()))
    {
      throw new SignatureException("Signature is expired");
    }

  } catch (CertificateException | CertPathValidatorException | IOException e) {
    throw new SignatureException(e);
  }
}
 
Example #14
Source File: TestZoneOffsetTransition.java    From threetenbp with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
@Test
public void test_isValidOffset_overlap() {
    LocalDateTime ldt = LocalDateTime.of(2010, 10, 31, 1, 0);
    ZoneOffsetTransition test = ZoneOffsetTransition.of(ldt, OFFSET_0300, OFFSET_0200);
    assertEquals(test.isValidOffset(OFFSET_0100), false);
    assertEquals(test.isValidOffset(OFFSET_0200), true);
    assertEquals(test.isValidOffset(OFFSET_0230), false);
    assertEquals(test.isValidOffset(OFFSET_0300), true);
    assertEquals(test.isValidOffset(OFFSET_0400), false);
}
 
Example #15
Source File: TestZoneOffsetTransitionRule.java    From threetenbp with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
@Test
public void test_createTransition_floatingWeekBackwards_seventhLast() {
    ZoneOffsetTransitionRule test = ZoneOffsetTransitionRule.of(
            Month.MARCH, -7, DayOfWeek.SUNDAY, TIME_0100, false, TimeDefinition.WALL,
            OFFSET_0200, OFFSET_0200, OFFSET_0300);
    ZoneOffsetTransition trans = new ZoneOffsetTransition(
            LocalDateTime.of(2000, Month.MARCH, 19, 1, 0), OFFSET_0200, OFFSET_0300);
    assertEquals(test.createTransition(2000), trans);
}
 
Example #16
Source File: TestZoneOffsetTransitionRule.java    From threetenbp with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
@Test
public void test_createTransition_floatingWeek_gap_notEndOfDay() {
    ZoneOffsetTransitionRule test = ZoneOffsetTransitionRule.of(
            Month.MARCH, 20, DayOfWeek.SUNDAY, TIME_0100, false, TimeDefinition.WALL,
            OFFSET_0200, OFFSET_0200, OFFSET_0300);
    ZoneOffsetTransition trans = new ZoneOffsetTransition(
            LocalDateTime.of(2000, Month.MARCH, 26, 1, 0), OFFSET_0200, OFFSET_0300);
    assertEquals(test.createTransition(2000), trans);
}
 
Example #17
Source File: TestStandardZoneRules.java    From threetenbp with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
public void test_Paris_getOffsetInfo_toDST() {
    ZoneRules test = europeParis();
    checkOffset(test, createLDT(2008, 3, 24), OFFSET_PONE, 1);
    checkOffset(test, createLDT(2008, 3, 25), OFFSET_PONE, 1);
    checkOffset(test, createLDT(2008, 3, 26), OFFSET_PONE, 1);
    checkOffset(test, createLDT(2008, 3, 27), OFFSET_PONE, 1);
    checkOffset(test, createLDT(2008, 3, 28), OFFSET_PONE, 1);
    checkOffset(test, createLDT(2008, 3, 29), OFFSET_PONE, 1);
    checkOffset(test, createLDT(2008, 3, 30), OFFSET_PONE, 1);
    checkOffset(test, createLDT(2008, 3, 31), OFFSET_PTWO, 1);
    // cutover at 01:00Z which is 02:00+01:00(local Paris time)
    checkOffset(test, LocalDateTime.of(2008, 3, 30, 1, 59, 59, 999999999), OFFSET_PONE, 1);
    checkOffset(test, LocalDateTime.of(2008, 3, 30, 3, 0, 0, 0), OFFSET_PTWO, 1);
}
 
Example #18
Source File: TestDateTimeTextPrinting.java    From threetenbp with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
@Test
public void test_print_appendText2arg_french_long() throws Exception {
    DateTimeFormatter f = builder.appendText(MONTH_OF_YEAR, TextStyle.FULL).toFormatter(Locale.FRENCH);
    LocalDateTime dt = LocalDateTime.of(2010, 1, 1, 0, 0);
    String text = f.format(dt);
    assertEquals(text, "janvier");
}
 
Example #19
Source File: DataProviderCacheTest.java    From droidconat-2016 with Apache License 2.0 5 votes vote down vote up
@Test
public void should_return_sessions_when_cache_time_is_still_active() {
    // Given
    cache.sessionsFetchedTime = LocalDateTime.now();
    cache.sessions = sessions;

    // When
    List<Session> result = cache.getSessions();

    // Then
    assertThat(result).isEqualTo(sessions);
}
 
Example #20
Source File: TestStandardZoneRules.java    From threetenbp with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
public void test_Paris_getOffsetInfo_fromDST() {
    ZoneRules test = europeParis();
    checkOffset(test, createLDT(2008, 10, 24), OFFSET_PTWO, 1);
    checkOffset(test, createLDT(2008, 10, 25), OFFSET_PTWO, 1);
    checkOffset(test, createLDT(2008, 10, 26), OFFSET_PTWO, 1);
    checkOffset(test, createLDT(2008, 10, 27), OFFSET_PONE, 1);
    checkOffset(test, createLDT(2008, 10, 28), OFFSET_PONE, 1);
    checkOffset(test, createLDT(2008, 10, 29), OFFSET_PONE, 1);
    checkOffset(test, createLDT(2008, 10, 30), OFFSET_PONE, 1);
    checkOffset(test, createLDT(2008, 10, 31), OFFSET_PONE, 1);
    // cutover at 01:00Z which is 02:00+01:00(local Paris time)
    checkOffset(test, LocalDateTime.of(2008, 10, 26, 1, 59, 59, 999999999), OFFSET_PTWO, 1);
    checkOffset(test, LocalDateTime.of(2008, 10, 26, 3, 0, 0, 0), OFFSET_PONE, 1);
}
 
Example #21
Source File: TestStandardZoneRules.java    From threetenbp with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
public void test_Dublin_getOffsetInfo_fromDST() {
    ZoneRules test = europeDublin();
    checkOffset(test, createLDT(2008, 10, 24), OFFSET_PONE, 1);
    checkOffset(test, createLDT(2008, 10, 25), OFFSET_PONE, 1);
    checkOffset(test, createLDT(2008, 10, 26), OFFSET_PONE, 1);
    checkOffset(test, createLDT(2008, 10, 27), OFFSET_ZERO, 1);
    checkOffset(test, createLDT(2008, 10, 28), OFFSET_ZERO, 1);
    checkOffset(test, createLDT(2008, 10, 29), OFFSET_ZERO, 1);
    checkOffset(test, createLDT(2008, 10, 30), OFFSET_ZERO, 1);
    checkOffset(test, createLDT(2008, 10, 31), OFFSET_ZERO, 1);
    // cutover at 01:00Z
    checkOffset(test, LocalDateTime.of(2008, 10, 26, 0, 59, 59, 999999999), OFFSET_PONE, 1);
    checkOffset(test, LocalDateTime.of(2008, 10, 26, 2, 0, 0, 0), OFFSET_ZERO, 1);
}
 
Example #22
Source File: TestStandardZoneRules.java    From threetenbp with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
public void test_Dublin_getOffsetInfo_toDST() {
    ZoneRules test = europeDublin();
    checkOffset(test, createLDT(2008, 3, 24), OFFSET_ZERO, 1);
    checkOffset(test, createLDT(2008, 3, 25), OFFSET_ZERO, 1);
    checkOffset(test, createLDT(2008, 3, 26), OFFSET_ZERO, 1);
    checkOffset(test, createLDT(2008, 3, 27), OFFSET_ZERO, 1);
    checkOffset(test, createLDT(2008, 3, 28), OFFSET_ZERO, 1);
    checkOffset(test, createLDT(2008, 3, 29), OFFSET_ZERO, 1);
    checkOffset(test, createLDT(2008, 3, 30), OFFSET_ZERO, 1);
    checkOffset(test, createLDT(2008, 3, 31), OFFSET_PONE, 1);
    // cutover at 01:00Z
    checkOffset(test, LocalDateTime.of(2008, 3, 30, 0, 59, 59, 999999999), OFFSET_ZERO, 1);
    checkOffset(test, LocalDateTime.of(2008, 3, 30, 2, 0, 0, 0), OFFSET_PONE, 1);
}
 
Example #23
Source File: AbstractTestPrinterParser.java    From threetenbp with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
@BeforeMethod
public void setUp() {
    printEmptyContext = new DateTimePrintContext(EMPTY, Locale.ENGLISH, DecimalStyle.STANDARD);
    ZonedDateTime zdt = LocalDateTime.of(2011, 6, 30, 12, 30, 40, 0).atZone(ZoneId.of("Europe/Paris"));
    printContext = new DateTimePrintContext(zdt, Locale.ENGLISH, DecimalStyle.STANDARD);
    parseContext = new DateTimeParseContext(Locale.ENGLISH, DecimalStyle.STANDARD, IsoChronology.INSTANCE);
    buf = new StringBuilder();
}
 
Example #24
Source File: TestDateTimeFormatters.java    From threetenbp with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
void setFields(LocalDateTime dt) {
    if (dt != null) {
        fields.put(YEAR, (long) dt.getYear());
        fields.put(MONTH_OF_YEAR, (long) dt.getMonthValue());
        fields.put(DAY_OF_MONTH, (long) dt.getDayOfMonth());
        fields.put(DAY_OF_YEAR, (long) dt.getDayOfYear());
        fields.put(DAY_OF_WEEK, (long) dt.getDayOfWeek().getValue());
        fields.put(IsoFields.WEEK_BASED_YEAR, dt.getLong(IsoFields.WEEK_BASED_YEAR));
        fields.put(IsoFields.WEEK_OF_WEEK_BASED_YEAR, dt.getLong(IsoFields.WEEK_OF_WEEK_BASED_YEAR));
        fields.put(HOUR_OF_DAY, (long) dt.getHour());
        fields.put(MINUTE_OF_HOUR, (long) dt.getMinute());
        fields.put(SECOND_OF_MINUTE, (long) dt.getSecond());
        fields.put(NANO_OF_SECOND, (long) dt.getNano());
    }
}
 
Example #25
Source File: CloudSnippets.java    From google-cloud-java with Apache License 2.0 5 votes vote down vote up
/** Example of running a query with timestamp query parameters. */
public void runQueryWithTimestampParameters() throws InterruptedException {
  // [START bigquery_query_params_timestamps]
  // BigQuery bigquery = BigQueryOptions.getDefaultInstance().getService();
  ZonedDateTime timestamp = LocalDateTime.of(2016, 12, 7, 8, 0, 0).atZone(ZoneOffset.UTC);
  String query = "SELECT TIMESTAMP_ADD(@ts_value, INTERVAL 1 HOUR);";
  // Note: Standard SQL is required to use query parameters.
  QueryJobConfiguration queryConfig =
      QueryJobConfiguration.newBuilder(query)
          .addNamedParameter(
              "ts_value",
              QueryParameterValue.timestamp(
                  // Timestamp takes microseconds since 1970-01-01T00:00:00 UTC
                  timestamp.toInstant().toEpochMilli() * 1000))
          .build();

  // Print the results.
  DateTimeFormatter formatter = DateTimeFormatter.ISO_INSTANT.withZone(ZoneOffset.UTC);
  for (FieldValueList row : bigquery.query(queryConfig).iterateAll()) {
    System.out.printf(
        "%s\n",
        formatter.format(
            Instant.ofEpochMilli(
                    // Timestamp values are returned in microseconds since 1970-01-01T00:00:00
                    // UTC,
                    // but org.joda.time.DateTime constructor accepts times in milliseconds.
                    row.get(0).getTimestampValue() / 1000)
                .atOffset(ZoneOffset.UTC)));
    System.out.printf("\n");
  }
  // [END bigquery_query_params_timestamps]
}
 
Example #26
Source File: ChronoZonedDateTimeImpl.java    From threetenbp with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
/**
 * Obtains an instance from a local date-time using the preferred offset if possible.
 *
 * @param localDateTime  the local date-time, not null
 * @param zone  the zone identifier, not null
 * @param preferredOffset  the zone offset, null if no preference
 * @return the zoned date-time, not null
 */
static <R extends ChronoLocalDate> ChronoZonedDateTime<R> ofBest(
        ChronoLocalDateTimeImpl<R> localDateTime, ZoneId zone, ZoneOffset preferredOffset) {
    Jdk8Methods.requireNonNull(localDateTime, "localDateTime");
    Jdk8Methods.requireNonNull(zone, "zone");
    if (zone instanceof ZoneOffset) {
        return new ChronoZonedDateTimeImpl<R>(localDateTime, (ZoneOffset) zone, zone);
    }
    ZoneRules rules = zone.getRules();
    LocalDateTime isoLDT = LocalDateTime.from(localDateTime);
    List<ZoneOffset> validOffsets = rules.getValidOffsets(isoLDT);
    ZoneOffset offset;
    if (validOffsets.size() == 1) {
        offset = validOffsets.get(0);
    } else if (validOffsets.size() == 0) {
        ZoneOffsetTransition trans = rules.getTransition(isoLDT);
        localDateTime = localDateTime.plusSeconds(trans.getDuration().getSeconds());
        offset = trans.getOffsetAfter();
    } else {
        if (preferredOffset != null && validOffsets.contains(preferredOffset)) {
            offset = preferredOffset;
        } else {
            offset = validOffsets.get(0);
        }
    }
    Jdk8Methods.requireNonNull(offset, "offset");  // protect against bad ZoneRules
    return new ChronoZonedDateTimeImpl<R>(localDateTime, offset, zone);
}
 
Example #27
Source File: ChronoZonedDateTimeImpl.java    From threetenbp with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
/**
 * Obtains an instance from an instant using the specified time-zone.
 *
 * @param chrono  the chronology, not null
 * @param instant  the instant, not null
 * @param zone  the zone identifier, not null
 * @return the zoned date-time, not null
 */
static <R extends ChronoLocalDate> ChronoZonedDateTimeImpl<R> ofInstant(Chronology chrono, Instant instant, ZoneId zone) {
    ZoneRules rules = zone.getRules();
    ZoneOffset offset = rules.getOffset(instant);
    Jdk8Methods.requireNonNull(offset, "offset");  // protect against bad ZoneRules
    LocalDateTime ldt = LocalDateTime.ofEpochSecond(instant.getEpochSecond(), instant.getNano(), offset);
    @SuppressWarnings("unchecked")
    ChronoLocalDateTimeImpl<R> cldt = (ChronoLocalDateTimeImpl<R>) chrono.localDateTime(ldt);
    return new ChronoZonedDateTimeImpl<R>(cldt, offset, zone);
}
 
Example #28
Source File: ChronoZonedDateTimeImpl.java    From threetenbp with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
@Override
public ChronoZonedDateTime<D> withEarlierOffsetAtOverlap() {
    ZoneOffsetTransition trans = getZone().getRules().getTransition(LocalDateTime.from(this));
    if (trans != null && trans.isOverlap()) {
        ZoneOffset earlierOffset = trans.getOffsetBefore();
        if (earlierOffset.equals(offset) == false) {
            return new ChronoZonedDateTimeImpl<D>(dateTime, earlierOffset, zone);
        }
    }
    return this;
}
 
Example #29
Source File: ChronoZonedDateTimeImpl.java    From threetenbp with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
@Override
public ChronoZonedDateTime<D> withLaterOffsetAtOverlap() {
    ZoneOffsetTransition trans = getZone().getRules().getTransition(LocalDateTime.from(this));
    if (trans != null) {
        ZoneOffset offset = trans.getOffsetAfter();
        if (offset.equals(getOffset()) == false) {
            return new ChronoZonedDateTimeImpl<D>(dateTime, offset, zone);
        }
    }
    return this;
}
 
Example #30
Source File: TestZoneOffsetTransition.java    From threetenbp with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
@Test
public void test_getters_gap() throws Exception {
    LocalDateTime before = LocalDateTime.of(2010, 3, 31, 1, 0);
    LocalDateTime after = LocalDateTime.of(2010, 3, 31, 2, 0);
    ZoneOffsetTransition test = ZoneOffsetTransition.of(before, OFFSET_0200, OFFSET_0300);
    assertEquals(test.isGap(), true);
    assertEquals(test.isOverlap(), false);
    assertEquals(test.getDateTimeBefore(), before);
    assertEquals(test.getDateTimeAfter(), after);
    assertEquals(test.getInstant(), before.toInstant(OFFSET_0200));
    assertEquals(test.getOffsetBefore(), OFFSET_0200);
    assertEquals(test.getOffsetAfter(), OFFSET_0300);
    assertEquals(test.getDuration(), Duration.of(1, HOURS));
    assertSerializable(test);
}