Java Code Examples for java.time.ZonedDateTime#format()

The following examples show how to use java.time.ZonedDateTime#format() . 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: DateProcessorTest.java    From sawmill with Apache License 2.0 6 votes vote down vote up
@Test
public void testOutputForamtUnix() {
    String field = "datetime";
    String targetField = "@timestamp";
    ZoneId zoneId = ZoneId.of("Europe/Paris");
    String outputFormat = "UNIX";
    ZonedDateTime zonedDateTime = LocalDateTime.now().atZone(zoneId);
    String iso8601Format = zonedDateTime.format(DateTimeFormatter.ofPattern("yyyy-MM-dd'T'HH:mm:ss,SSS"));
    Doc doc = createDoc(field, iso8601Format);

    Map<String,Object> config = createConfig("field", field,
            "targetField", targetField,
            "formats", Arrays.asList("ISO8601"),
            "outputFormat", outputFormat,
            "timeZone", zoneId.toString());

    DateProcessor dateProcessor = createProcessor(DateProcessor.class, config);

    assertThat(dateProcessor.process(doc).isSucceeded()).isTrue();
    assertThat((String)doc.getField(targetField)).isEqualTo(zonedDateTime.format(DateProcessor.UNIX));
}
 
Example 2
Source File: NTGVisitorEncode.java    From sailfish-core with Apache License 2.0 6 votes vote down vote up
@Override
public void visit(String fieldName, LocalDateTime value, IFieldStructure fldStruct, boolean isDefault) {
    
    if (logger.isDebugEnabled()) {
        logger.debug("   Encode visiting String field [{}] , value = [{}]", fieldName, value == null ? "" : value);
    }
    
    validateAttributesMap(fieldName, LocalDateTime.class, fldStruct);
    
    int length = getAttributeValue(fldStruct, NTGProtocolAttribute.Length.toString());
    int offset = getAttributeValue(fldStruct, NTGProtocolAttribute.Offset.toString());
    String dateTimeFormat = getAttributeValue(fldStruct, NTGProtocolAttribute.DateTimeFormat.toString());
    
    validateOffset(fieldName, accumulatedLength, offset);
    
    DateTimeFormatter dateTimeFormatter = DateTimeUtility.createFormatter(dateTimeFormat);
    ZonedDateTime zonedDateTime = DateTimeUtility.toZonedDateTime(value);
    String dateTimeStr = zonedDateTime.format(dateTimeFormatter);
    byte[] dateTimeBytes = dateTimeStr.getBytes();
    checkLength(dateTimeStr, dateTimeBytes.length, length);
    buffer.put(dateTimeBytes);
    accumulatedLength += length;
}
 
Example 3
Source File: RootInformationController.java    From metamodel-membrane with Apache License 2.0 5 votes vote down vote up
private HelloResponseServertime getServerTime() {
    final ZonedDateTime now = ZonedDateTime.now();
    final String dateFormatted = now.format(DateTimeFormatter.ISO_INSTANT);

    final HelloResponseServertime serverTime = new HelloResponseServertime();
    serverTime.timestamp(new Date().getTime());
    serverTime.iso8601(dateFormatted);
    return serverTime;
}
 
Example 4
Source File: HttpServerDefaultHeadersTest.java    From armeria with Apache License 2.0 5 votes vote down vote up
private static boolean isValidDateTimeFormat(String dateTimeString) {
    try {
        final ZonedDateTime parsedDateTime =
                ZonedDateTime.parse(dateTimeString, DateTimeFormatter.RFC_1123_DATE_TIME);
        final String parsedDateTimeString = parsedDateTime.format(DateTimeFormatter.RFC_1123_DATE_TIME);
        return parsedDateTimeString.equals(dateTimeString);
    } catch (DateTimeException e) {
        return false;
    }
}
 
Example 5
Source File: InstantToStringConverter.java    From konker-platform with Apache License 2.0 5 votes vote down vote up
@Override
public String convert(Instant source) {
    ZonedDateTime zonedTime = source.atZone(ZoneId.of(utils.getUserZoneID()));
    return zonedTime
            .format(DateTimeFormatter.ofPattern(
                    utils.getDateTimeFormatPattern(),
                    utils.getCurrentLocale()
                    )
            );
}
 
Example 6
Source File: WalletUtils.java    From blockchain with Apache License 2.0 5 votes vote down vote up
private static String getWalletFileName(WalletFile walletFile) {
    DateTimeFormatter format = DateTimeFormatter.ofPattern(
            "'UTC--'yyyy-MM-dd'T'HH-mm-ss.nVV'--'");
    ZonedDateTime now = ZonedDateTime.now(ZoneOffset.UTC);

    return now.format(format) + walletFile.getAddress() + ".json";
}
 
Example 7
Source File: TopicPartitionRecordGrouperTest.java    From aiven-kafka-connect-gcs with GNU Affero General Public License v3.0 4 votes vote down vote up
@Test
void rotateKeysMonthly() {
    final Template filenameTemplate =
        Template.of(
            "{{topic}}-"
                + "{{partition}}-"
                + "{{start_offset}}-"
                + "{{timestamp:unit=YYYY}}"
                + "{{timestamp:unit=MM}}"
        );
    final TimestampSource timestampSourceMock = mock(TimestampSource.class);

    final ZonedDateTime firstMonthTime = ZonedDateTime.now().with(TemporalAdjusters.lastDayOfMonth());
    final ZonedDateTime secondMonth = firstMonthTime.plusDays(1);
    final String firstMonthTs =
        firstMonthTime.format(DateTimeFormatter.ofPattern("YYYY"))
            + firstMonthTime.format(DateTimeFormatter.ofPattern("MM"));
    final String secondMonthTs =
        secondMonth.format(DateTimeFormatter.ofPattern("YYYY"))
            + secondMonth.format(DateTimeFormatter.ofPattern("MM"));

    when(timestampSourceMock.time()).thenReturn(firstMonthTime);
    final TopicPartitionRecordGrouper grouper =
        new TopicPartitionRecordGrouper(
            filenameTemplate,
            null,
            timestampSourceMock
        );

    grouper.put(T0P1R0);
    grouper.put(T0P1R1);
    grouper.put(T0P1R2);

    when(timestampSourceMock.time()).thenReturn(secondMonth);

    grouper.put(T0P1R3);

    final Map<String, List<SinkRecord>> records = grouper.records();

    assertEquals(2, records.size());

    assertThat(
        records.keySet(),
        containsInAnyOrder(
            "topic0-1-10-" + firstMonthTs,
            "topic0-1-10-" + secondMonthTs
        )
    );
    assertThat(
        records.get("topic0-1-10-" + firstMonthTs),
        contains(T0P1R0, T0P1R1, T0P1R2)
    );
    assertThat(
        records.get("topic0-1-10-" + secondMonthTs),
        contains(T0P1R3)
    );
}
 
Example 8
Source File: TopicPartitionRecordGrouperTest.java    From aiven-kafka-connect-gcs with GNU Affero General Public License v3.0 4 votes vote down vote up
@Test
void rotateKeysYearly() {
    final Template filenameTemplate =
        Template.of(
            "{{topic}}-"
                + "{{partition}}-"
                + "{{start_offset}}-"
                + "{{timestamp:unit=YYYY}}"
                + "{{timestamp:unit=MM}}"
        );
    final TimestampSource timestampSourceMock = mock(TimestampSource.class);

    final ZonedDateTime firstYearTime = ZonedDateTime.now();
    final ZonedDateTime secondYearMonth = firstYearTime.plusYears(1);
    final String firstYearTs =
        firstYearTime.format(DateTimeFormatter.ofPattern("YYYY"))
            + firstYearTime.format(DateTimeFormatter.ofPattern("MM"));
    final String secondYearTs =
        secondYearMonth.format(DateTimeFormatter.ofPattern("YYYY"))
            + secondYearMonth.format(DateTimeFormatter.ofPattern("MM"));

    when(timestampSourceMock.time()).thenReturn(firstYearTime);
    final TopicPartitionRecordGrouper grouper =
        new TopicPartitionRecordGrouper(
            filenameTemplate,
            null,
            timestampSourceMock
        );

    grouper.put(T0P1R0);
    grouper.put(T0P1R1);
    grouper.put(T0P1R2);

    when(timestampSourceMock.time()).thenReturn(secondYearMonth);

    grouper.put(T0P1R3);

    final Map<String, List<SinkRecord>> records = grouper.records();

    assertEquals(2, records.size());

    assertThat(
        records.keySet(),
        containsInAnyOrder(
            "topic0-1-10-" + firstYearTs,
            "topic0-1-10-" + secondYearTs
        )
    );
    assertThat(
        records.get("topic0-1-10-" + firstYearTs),
        contains(T0P1R0, T0P1R1, T0P1R2)
    );
    assertThat(
        records.get("topic0-1-10-" + secondYearTs),
        contains(T0P1R3)
    );
}
 
Example 9
Source File: FormattedTimestamp.java    From strongbox with Apache License 2.0 4 votes vote down vote up
public static String nowUTC() {
    ZonedDateTime localNow = ZonedDateTime.now();
    ZonedDateTime utcNow = localNow.withZoneSameInstant(utc);
    return utcNow.format(comparableFormatter);
}
 
Example 10
Source File: DeletedMessageWithStorageInformationDTO.java    From james-project with Apache License 2.0 4 votes vote down vote up
private static String serializeZonedDateTime(ZonedDateTime time) {
    return time.format(DateTimeFormatter.ISO_ZONED_DATE_TIME);
}
 
Example 11
Source File: XMLDateTimeAdapter.java    From g-suite-identity-sync with Apache License 2.0 4 votes vote down vote up
public static String printDateTime(ZonedDateTime time) {
    return time.format(ISO_INSTANT);
}
 
Example 12
Source File: Utility.java    From mercury with Apache License 2.0 4 votes vote down vote up
public String getTimestamp(long time) {
    ZonedDateTime zdt = ZonedDateTime.ofInstant(Instant.ofEpochMilli(time), UTC_TIME);
    return zdt.format(TIMESTAMP);
}
 
Example 13
Source File: TopicPartitionRecordGrouperTest.java    From aiven-kafka-connect-gcs with GNU Affero General Public License v3.0 4 votes vote down vote up
@Test
void rotateKeysDaily() {
    final Template filenameTemplate =
        Template.of(
            "{{topic}}-"
                + "{{partition}}-"
                + "{{start_offset}}-"
                + "{{timestamp:unit=YYYY}}"
                + "{{timestamp:unit=MM}}"
                + "{{timestamp:unit=dd}}"
        );
    final TimestampSource timestampSourceMock = mock(TimestampSource.class);

    final ZonedDateTime firstDayTime = ZonedDateTime.now();
    final ZonedDateTime secondDayTime = firstDayTime.plusDays(1);
    final String firstDayTs =
        firstDayTime.format(DateTimeFormatter.ofPattern("YYYY"))
            + firstDayTime.format(DateTimeFormatter.ofPattern("MM"))
            + firstDayTime.format(DateTimeFormatter.ofPattern("dd"));
    final String secondDayTs =
        secondDayTime.format(DateTimeFormatter.ofPattern("YYYY"))
            + secondDayTime.format(DateTimeFormatter.ofPattern("MM"))
            + secondDayTime.format(DateTimeFormatter.ofPattern("dd"));

    when(timestampSourceMock.time()).thenReturn(firstDayTime);
    final TopicPartitionRecordGrouper grouper =
        new TopicPartitionRecordGrouper(
            filenameTemplate,
            null,
            timestampSourceMock
        );

    grouper.put(T0P1R0);
    grouper.put(T0P1R1);
    grouper.put(T0P1R2);

    when(timestampSourceMock.time()).thenReturn(secondDayTime);

    grouper.put(T0P1R3);

    final Map<String, List<SinkRecord>> records = grouper.records();

    assertEquals(2, records.size());

    assertThat(
        records.keySet(),
        containsInAnyOrder(
            "topic0-1-10-" + firstDayTs,
            "topic0-1-10-" + secondDayTs
        )
    );
    assertThat(
        records.get("topic0-1-10-" + firstDayTs),
        contains(T0P1R0, T0P1R1, T0P1R2)
    );
    assertThat(
        records.get("topic0-1-10-" + secondDayTs),
        contains(T0P1R3)
    );
}
 
Example 14
Source File: TopicPartitionRecordGrouperTest.java    From aiven-kafka-connect-gcs with GNU Affero General Public License v3.0 4 votes vote down vote up
@Test
void rotateKeysHourly() {
    final Template filenameTemplate =
        Template.of(
            "{{topic}}-"
                + "{{partition}}-"
                + "{{start_offset}}-"
                + "{{timestamp:unit=YYYY}}"
                + "{{timestamp:unit=MM}}"
                + "{{timestamp:unit=dd}}"
                + "{{timestamp:unit=HH}}"
        );
    final TimestampSource timestampSourceMock = mock(TimestampSource.class);

    final ZonedDateTime firstHourTime = ZonedDateTime.now();
    final ZonedDateTime secondHourTime = firstHourTime.plusHours(1);
    final String firstHourTs =
        firstHourTime.format(DateTimeFormatter.ofPattern("YYYY"))
            + firstHourTime.format(DateTimeFormatter.ofPattern("MM"))
            + firstHourTime.format(DateTimeFormatter.ofPattern("dd"))
            + firstHourTime.format(DateTimeFormatter.ofPattern("HH"));
    final String secondHourTs =
        secondHourTime.format(DateTimeFormatter.ofPattern("YYYY"))
            + secondHourTime.format(DateTimeFormatter.ofPattern("MM"))
            + secondHourTime.format(DateTimeFormatter.ofPattern("dd"))
            + secondHourTime.format(DateTimeFormatter.ofPattern("HH"));

    when(timestampSourceMock.time()).thenReturn(firstHourTime);
    final TopicPartitionRecordGrouper grouper =
        new TopicPartitionRecordGrouper(
            filenameTemplate,
            null,
            timestampSourceMock
        );

    grouper.put(T0P0R1);
    grouper.put(T0P0R2);
    grouper.put(T0P0R3);

    when(timestampSourceMock.time()).thenReturn(secondHourTime);

    grouper.put(T0P0R4);
    grouper.put(T0P0R5);

    final Map<String, List<SinkRecord>> records = grouper.records();

    assertEquals(2, records.size());

    assertThat(
        records.keySet(),
        containsInAnyOrder(
            "topic0-0-1-" + firstHourTs,
            "topic0-0-1-" + secondHourTs
        )
    );
    assertThat(
        records.get("topic0-0-1-" + firstHourTs),
        contains(T0P0R1, T0P0R2, T0P0R3)
    );
    assertThat(
        records.get("topic0-0-1-" + secondHourTs),
        contains(T0P0R4, T0P0R5)
    );
}
 
Example 15
Source File: TopicPartitionRecordGrouperTest.java    From aiven-kafka-connect-gcs with GNU Affero General Public License v3.0 4 votes vote down vote up
@Test
final void addTimeUnitsToTheFileName() {
    final Template filenameTemplate =
        Template.of(
            "{{topic}}-"
                + "{{partition}}-"
                + "{{start_offset}}-"
                + "{{timestamp:unit=YYYY}}"
                + "{{timestamp:unit=MM}}"
                + "{{timestamp:unit=dd}}"
        );
    final ZonedDateTime t = TimestampSource.of(TimestampSource.Type.WALLCLOCK).time();
    final String expectedTs =
        t.format(DateTimeFormatter.ofPattern("YYYY"))
            + t.format(DateTimeFormatter.ofPattern("MM"))
            + t.format(DateTimeFormatter.ofPattern("dd"));

    final TopicPartitionRecordGrouper grouper =
        new TopicPartitionRecordGrouper(
            filenameTemplate,
            null,
            TimestampSource.of(TimestampSource.Type.WALLCLOCK)
        );

    grouper.put(T1P1R0);
    grouper.put(T1P1R1);
    grouper.put(T0P0R4);
    grouper.put(T1P1R2);
    grouper.put(T1P1R3);
    grouper.put(T0P0R5);

    final Map<String, List<SinkRecord>> records = grouper.records();

    assertThat(
        records.keySet(),
        containsInAnyOrder(
            "topic0-0-4-" + expectedTs,
            "topic1-0-1000-" + expectedTs
        )
    );
    assertThat(
        records.keySet(),
        containsInAnyOrder(
            "topic0-0-4-" + expectedTs,
            "topic1-0-1000-" + expectedTs
        )
    );
    assertThat(
        records.get("topic0-0-4-" + expectedTs),
        contains(T0P0R4, T0P0R5)
    );
    assertThat(
        records.get("topic1-0-1000-" + expectedTs),
        contains(T1P1R0, T1P1R1, T1P1R2, T1P1R3)
    );
}
 
Example 16
Source File: ParquetResolverTest.java    From pxf with Apache License 2.0 4 votes vote down vote up
@Test
public void testGetFields_Primitive_Repeated_Synthetic() {
    // this test does not read the actual Parquet file, but rather construct Group object synthetically
    schema = getParquetSchemaForPrimitiveTypes(Type.Repetition.REPEATED, true);
    // schema has changed, set metadata again
    context.setMetadata(schema);
    context.setTupleDescription(getColumnDescriptorsFromSchema(schema));
    resolver.initialize(context);

    /*
    Corresponding DB column types  are:
    TEXT,TEXT,INTEGER, DOUBLE PRECISION,NUMERIC,TIMESTAMP,REAL,BIGINT,BOOLEAN,SMALLINT,SMALLINT,VARCHAR(5),CHAR(3),BYTEA
     */

    Group group = new SimpleGroup(schema);

    group.add(0, "row1-1");
    group.add(0, "row1-2");

    // leave column 1 (t2) unset as part fo the test

    group.add(2, 1);
    group.add(2, 2);
    group.add(2, 3);

    group.add(3, 6.0d);
    group.add(3, -16.34d);

    BigDecimal value = new BigDecimal("12345678.9012345987654321"); // place of dot doesn't matter
    byte fillByte = (byte) (value.signum() < 0 ? 0xFF : 0x00);
    byte[] unscaled = value.unscaledValue().toByteArray();
    byte[] bytes = new byte[16];
    int offset = bytes.length - unscaled.length;
    for (int i = 0; i < bytes.length; i += 1) {
        bytes[i] = (i < offset) ? fillByte : unscaled[i - offset];
    }
    group.add(4, Binary.fromReusedByteArray(bytes));

    group.add(5, ParquetTypeConverter.getBinaryFromTimestamp("2019-03-14 14:10:28"));
    group.add(5, ParquetTypeConverter.getBinaryFromTimestamp("1969-12-30 05:42:23.211211"));

    group.add(6, 7.7f);
    group.add(6, -12345.35354646f);

    group.add(7, 23456789L);
    group.add(7, -123456789012345L);

    group.add(8, true);
    group.add(8, false);

    group.add(9, (short) 1);
    group.add(9, (short) -3);

    group.add(10, (short) 269);
    group.add(10, (short) -313);

    group.add(11, Binary.fromString("Hello"));
    group.add(11, Binary.fromString("World"));

    group.add(12, Binary.fromString("foo"));
    group.add(12, Binary.fromString("bar"));

    byte[] byteArray1 = new byte[]{(byte) 49, (byte) 50, (byte) 51};
    group.add(13, Binary.fromReusedByteArray(byteArray1, 0, 3));
    byte[] byteArray2 = new byte[]{(byte) 52, (byte) 53, (byte) 54};
    group.add(13, Binary.fromReusedByteArray(byteArray2, 0, 3));

    group.add(14, ParquetTypeConverter.getBinaryFromTimestampWithTimeZone("2019-03-14 14:10:28+07"));
    OffsetDateTime offsetDateTime1 = OffsetDateTime.parse("2019-03-14T14:10:28+07:00");
    ZonedDateTime localDateTime1 = offsetDateTime1.atZoneSameInstant(ZoneId.systemDefault());
    String localDateTimeString1 = localDateTime1.format(DateTimeFormatter.ofPattern("[yyyy-MM-dd HH:mm:ss]"));

    group.add(15, ParquetTypeConverter.getBinaryFromTimestampWithTimeZone("2019-03-14 14:10:28-07:30"));
    OffsetDateTime offsetDateTime2 = OffsetDateTime.parse("2019-03-14T14:10:28-07:30");
    ZonedDateTime localDateTime2 = offsetDateTime2.atZoneSameInstant(ZoneId.systemDefault());
    String localDateTimeString2 = localDateTime2.format(DateTimeFormatter.ofPattern("[yyyy-MM-dd HH:mm:ss]"));


    List<Group> groups = new ArrayList<>();
    groups.add(group);
    List<OneField> fields = assertRow(groups, 0, 16);

    assertField(fields, 0, "[\"row1-1\",\"row1-2\"]", DataType.TEXT);
    assertField(fields, 1, "[]", DataType.TEXT);
    assertField(fields, 2, "[1,2,3]", DataType.TEXT);
    assertField(fields, 3, "[6.0,-16.34]", DataType.TEXT);
    assertField(fields, 4, "[123456.789012345987654321]", DataType.TEXT); // scale fixed to 18 in schema
    assertField(fields, 5, "[\"2019-03-14 14:10:28\",\"1969-12-30 05:42:23.211211\"]", DataType.TEXT);
    assertField(fields, 6, "[7.7,-12345.354]", DataType.TEXT); // rounded to the precision of 8
    assertField(fields, 7, "[23456789,-123456789012345]", DataType.TEXT);
    assertField(fields, 8, "[true,false]", DataType.TEXT);
    assertField(fields, 9, "[1,-3]", DataType.TEXT);
    assertField(fields, 10, "[269,-313]", DataType.TEXT);
    assertField(fields, 11, "[\"Hello\",\"World\"]", DataType.TEXT);
    assertField(fields, 12, "[\"foo\",\"bar\"]", DataType.TEXT); // 3 chars only
    Base64.Encoder encoder = Base64.getEncoder(); // byte arrays are Base64 encoded into strings
    String expectedByteArrays = "[\"" + encoder.encodeToString(byteArray1) + "\",\"" + encoder.encodeToString(byteArray2) + "\"]";
    assertField(fields, 13, expectedByteArrays, DataType.TEXT);
    assertField(fields, 14, "[\"" + localDateTimeString1 + "\"]", DataType.TEXT);
    assertField(fields, 15, "[\"" + localDateTimeString2 + "\"]", DataType.TEXT);
}
 
Example 17
Source File: ClientSideRequestStatistics.java    From azure-cosmosdb-java with MIT License 4 votes vote down vote up
private static String formatDateTime(ZonedDateTime dateTime) {
    if (dateTime == null) {
        return null;
    }
    return dateTime.format(responseTimeFormatter);
}
 
Example 18
Source File: FormattedTimestamp.java    From strongbox with Apache License 2.0 4 votes vote down vote up
public static String toHumanReadable(ZonedDateTime timestamp) {
    return timestamp.format(humanReadableFormatter);
}
 
Example 19
Source File: TimeUtil.java    From game-server with MIT License 2 votes vote down vote up
/**
 * 带时区的时间
 * @param zonedDateTime
 * @param formatter
 * @return
 */
public static String getDateTimeFormat(ZonedDateTime zonedDateTime, DateTimeFormatter formatter) {
    return zonedDateTime.format(formatter);
}
 
Example 20
Source File: Utils.java    From td-ameritrade-client with Apache License 2.0 2 votes vote down vote up
/**
 *
 * @param zonedDateTime the date to format
 * @return a string formatted like {@code yyyy-MM-dd}.
 */
public static String toTdaYMD(ZonedDateTime zonedDateTime) {
  return zonedDateTime.format(TMD);
}