public static Date toDate(String time, String pattern) { LocalDate formatted = LocalDate.parse(time, DateTimeFormatter.ofPattern(pattern)); return Date.from(Instant.from(formatted.atStartOfDay(ZoneId.systemDefault()))); }
private static void raw(Exchange bfx) throws IOException { /* BitfinexTradeServiceRaw tradeService = (BitfinexTradeServiceRaw) bfx.getTradeService(); LimitOrder limitOrder = new LimitOrder.Builder(OrderType.BID, CurrencyPair.BTC_USD).limitPrice(new BigDecimal("481.69")) .originalAmount(new BigDecimal("0.001")).build(); tradeService.placeBitfinexLimitOrder(limitOrder, BitfinexOrderType.LIMIT); */ BitfinexTradeServiceRaw tradeService = (BitfinexTradeServiceRaw) bfx.getTradeService(); Date tenDaysAgo = Date.from(LocalDate.now().minusDays(10).atStartOfDay(ZoneId.systemDefault()).toInstant()); BitfinexFundingTradeResponse[] fundingTradeResponses = tradeService.getBitfinexFundingHistory("USD", tenDaysAgo, 2000); } }
@Nonnull @Override public LocalDate getEnd() { return LocalDate.of(2019, 1, 1); }
@JsonValue @Override public String toString() { return LocalDate.ofEpochDay(days).toString(); } }
@Test public void testSimpleRetentionQuery() throws Exception { QueryResult result = getRetentionQueryExecutor().query(CONTEXT, Optional.empty(), Optional.empty(), DAY, Optional.empty(), Optional.of(15), LocalDate.ofEpochDay(0), LocalDate.ofEpochDay(SCALE_FACTOR), ZoneOffset.UTC, false) .getResult().join(); assertFalse(result.isFailed()); assertEquals(result.getResult(), of( asList(LocalDate.parse("1970-01-01"), null, 1L), asList(LocalDate.parse("1970-01-01"), 1L, 1L), asList(LocalDate.parse("1970-01-02"), null, 1L), asList(LocalDate.parse("1970-01-03"), null, 1L))); }
@Test public void testConvertTime() throws SQLException { LocalTime time = LocalTime.of(12, 34, 56); Time sqlTime = Time.valueOf(time); java.util.Date javaDate = new java.util.Date(sqlTime.getTime()); LocalDateTime dateTime = LocalDateTime.of(LocalDate.of(2001, 5, 6), time); Timestamp sqlTimestamp = Timestamp.valueOf(dateTime); assertParameter(sqlTime, Types.TIME, (ps, i) -> ps.setTime(i, sqlTime)); assertParameter(sqlTime, Types.TIME, (ps, i) -> ps.setObject(i, sqlTime)); assertParameter(sqlTime, Types.TIME, (ps, i) -> ps.setObject(i, sqlTime, Types.TIME)); assertParameter(sqlTime, Types.TIME, (ps, i) -> ps.setObject(i, sqlTimestamp, Types.TIME)); assertParameter(sqlTime, Types.TIME, (ps, i) -> ps.setObject(i, javaDate, Types.TIME)); assertParameter(sqlTime, Types.TIME, (ps, i) -> ps.setObject(i, dateTime, Types.TIME)); assertParameter(sqlTime, Types.TIME, (ps, i) -> ps.setObject(i, "12:34:56", Types.TIME)); }
@Test public void testGetAttributesWithTime() { getMetastore().createProject(PROJECT_NAME); getMetastore().getOrCreateCollectionFields(PROJECT_NAME, "test", ImmutableSet.of(new SchemaField("_time", TIMESTAMP), new SchemaField("test", STRING))); ImmutableSet<SchemaField> schema = ImmutableSet.of(new SchemaField("test", STRING)); getMetastore().getOrCreateCollectionFields(PROJECT_NAME, "test", schema); assertEquals(getMetastore().getAttributes(PROJECT_NAME, "test", "test", Optional.of(LocalDate.parse("2017-01-01")), Optional.of(LocalDate.parse("2017-02-01")), Optional.empty()).join().size(), 0); }
@Test public void testReferenceGrouping() throws Exception { .put(DAY_OF_WEEK, ImmutableSet.of(of("Thursday", "test", 100L))) .put(HOUR, ImmutableSet.of(of(parse("1970-01-01T00:00:00Z"), "test", 36L), of(parse("1970-01-01T01:00:00Z"), "test", 36L), of(parse("1970-01-01T02:00:00Z"), "test", 28L))) .put(DAY, ImmutableSet.of(of(LocalDate.parse("1970-01-01"), "test", 100L))) .put(WEEK, ImmutableSet.of(of(LocalDate.parse("1969-12-29"), "test", 100L))) .put(MONTH, ImmutableSet.of(of(LocalDate.parse("1970-01-01"), "test", 100L))) .put(YEAR, ImmutableSet.of(of(LocalDate.parse("1970-01-01"), "test", 100L))) .build(); Optional<TimestampTransformation> trans = fromPrettyName(dimension); if (trans.isPresent()) { QueryResult test = getEventExplorer().analyze(new RequestContext(PROJECT_NAME, null), of("test"), new EventExplorer.Measure("teststr", AggregationType.APPROXIMATE_UNIQUE), new EventExplorer.Reference(EventExplorer.ReferenceType.REFERENCE, trans.get().getPrettyName()), null, null, LocalDate.ofEpochDay(0), LocalDate.ofEpochDay(SCALE_FACTOR), ZoneOffset.UTC).getResult().join(); assertFalse(test.isFailed()); assertEquals(copyOf(test.getResult()), GROUPING.get(trans.get())); } else {
import java.time.Instant; import java.time.LocalDate; import java.time.LocalDateTime; import java.time.ZoneId; import java.util.Date; public class DateUtils { public static Date asDate(LocalDate localDate) { return Date.from(localDate.atStartOfDay().atZone(ZoneId.systemDefault()).toInstant()); } public static Date asDate(LocalDateTime localDateTime) { return Date.from(localDateTime.atZone(ZoneId.systemDefault()).toInstant()); } public static LocalDate asLocalDate(Date date) { return Instant.ofEpochMilli(date.getTime()).atZone(ZoneId.systemDefault()).toLocalDate(); } public static LocalDateTime asLocalDateTime(Date date) { return Instant.ofEpochMilli(date.getTime()).atZone(ZoneId.systemDefault()).toLocalDateTime(); } }
public static long dateToLong(Object datelike) { if (datelike instanceof Date) { Date date = (Date) datelike; return date.getTime(); } else if (datelike instanceof Calendar) { Calendar calendar = (Calendar) datelike; return calendar.getTimeInMillis(); } else if (datelike instanceof Instant) { Instant instant = (Instant) datelike; return instant.toEpochMilli(); } else if (datelike instanceof LocalDateTime) { LocalDateTime date = (LocalDateTime) datelike; return date.atZone(ZoneId.of("UTC")).toInstant().toEpochMilli(); } else if (datelike instanceof LocalDate) { LocalDate date = (LocalDate) datelike; return date.atStartOfDay(ZoneId.of("UTC")).toInstant().toEpochMilli(); } else { throw new IllegalArgumentException("Illegal argument " + datelike + ". Expected a Number, Date, Instant, LocalDateTime, or LocalDate"); } }
@Test(dataProvider = "stubOn") public void test_stub_overnight(OvernightIborSwapConvention convention, Tenor tenor) { LocalDate tradeDate = LocalDate.of(2015, 10, 20); SwapTrade swap = convention.createTrade(tradeDate, tenor, BuySell.BUY, 1, 0.01, REF_DATA); ResolvedSwap swapResolved = swap.getProduct().resolve(REF_DATA); LocalDate endDate = swapResolved.getLeg(PayReceive.PAY).get().getEndDate(); assertTrue(endDate.isAfter(tradeDate.plus(tenor).minusDays(7))); assertTrue(endDate.isBefore(tradeDate.plus(tenor).plusDays(7))); }
@Test(dataProvider = "stubIbor") public void test_stub_ibor(FixedIborSwapConvention convention, Tenor tenor) { LocalDate tradeDate = LocalDate.of(2015, 10, 20); SwapTrade swap = convention.createTrade(tradeDate, tenor, BuySell.BUY, 1, 0.01, REF_DATA); ResolvedSwap swapResolved = swap.getProduct().resolve(REF_DATA); LocalDate endDate = swapResolved.getLeg(PayReceive.PAY).get().getEndDate(); assertTrue(endDate.isAfter(tradeDate.plus(tenor).minusMonths(1))); assertTrue(endDate.isBefore(tradeDate.plus(tenor).plusMonths(1))); }
/** * Converts local date to Date. */ public static Date toDate(final LocalDate localDate) { return Date.from(localDate.atStartOfDay(ZoneId.systemDefault()).toInstant()); } /**
@Test public void testLocallyUnrepresentableTimeLiterals() { LocalDateTime localTimeThatDidNotExist = LocalDateTime.of(2017, 4, 2, 2, 10); checkState(ZoneId.systemDefault().getRules().getValidOffsets(localTimeThatDidNotExist).isEmpty(), "This test assumes certain JVM time zone"); // This tests that both Presto runner and H2 can return TIMESTAMP value that never happened in JVM's zone (e.g. is not representable using java.sql.Timestamp) @Language("SQL") String sql = DateTimeFormatter.ofPattern("'SELECT TIMESTAMP '''uuuu-MM-dd HH:mm:ss''").format(localTimeThatDidNotExist); assertEquals(computeScalar(sql), localTimeThatDidNotExist); // this tests Presto and the QueryRunner assertQuery(sql); // this tests H2QueryRunner LocalDate localDateThatDidNotHaveMidnight = LocalDate.of(1970, 1, 1); checkState(ZoneId.systemDefault().getRules().getValidOffsets(localDateThatDidNotHaveMidnight.atStartOfDay()).isEmpty(), "This test assumes certain JVM time zone"); // This tests that both Presto runner and H2 can return DATE value for a day which midnight never happened in JVM's zone (e.g. is not exactly representable using java.sql.Date) sql = DateTimeFormatter.ofPattern("'SELECT DATE '''uuuu-MM-dd''").format(localDateThatDidNotHaveMidnight); assertEquals(computeScalar(sql), localDateThatDidNotHaveMidnight); // this tests Presto and the QueryRunner assertQuery(sql); // this tests H2QueryRunner LocalTime localTimeThatDidNotOccurOn19700101 = LocalTime.of(0, 10); checkState(ZoneId.systemDefault().getRules().getValidOffsets(localTimeThatDidNotOccurOn19700101.atDate(LocalDate.ofEpochDay(0))).isEmpty(), "This test assumes certain JVM time zone"); checkState(!Objects.equals(java.sql.Time.valueOf(localTimeThatDidNotOccurOn19700101).toLocalTime(), localTimeThatDidNotOccurOn19700101), "This test assumes certain JVM time zone"); sql = DateTimeFormatter.ofPattern("'SELECT TIME '''HH:mm:ss''").format(localTimeThatDidNotOccurOn19700101); assertEquals(computeScalar(sql), localTimeThatDidNotOccurOn19700101); // this tests Presto and the QueryRunner assertQuery(sql); // this tests H2QueryRunner } }
@Test public void testDate() { // Note: there is identical test for PostgreSQL ZoneId jvmZone = ZoneId.systemDefault(); checkState(jvmZone.getId().equals("America/Bahia_Banderas"), "This test assumes certain JVM time zone"); LocalDate dateOfLocalTimeChangeForwardAtMidnightInJvmZone = LocalDate.of(1970, 1, 1); verify(jvmZone.getRules().getValidOffsets(dateOfLocalTimeChangeForwardAtMidnightInJvmZone.atStartOfDay()).isEmpty()); ZoneId someZone = ZoneId.of("Europe/Vilnius"); LocalDate dateOfLocalTimeChangeForwardAtMidnightInSomeZone = LocalDate.of(1983, 4, 1); verify(someZone.getRules().getValidOffsets(dateOfLocalTimeChangeForwardAtMidnightInSomeZone.atStartOfDay()).isEmpty()); LocalDate dateOfLocalTimeChangeBackwardAtMidnightInSomeZone = LocalDate.of(1983, 10, 1); verify(someZone.getRules().getValidOffsets(dateOfLocalTimeChangeBackwardAtMidnightInSomeZone.atStartOfDay().minusMinutes(1)).size() == 2); DataTypeTest testCases = DataTypeTest.create() .addRoundTrip(dateDataType(), LocalDate.of(1952, 4, 3)) // before epoch .addRoundTrip(dateDataType(), LocalDate.of(1970, 1, 1)) .addRoundTrip(dateDataType(), LocalDate.of(1970, 2, 3)) .addRoundTrip(dateDataType(), LocalDate.of(2017, 7, 1)) // summer on northern hemisphere (possible DST) .addRoundTrip(dateDataType(), LocalDate.of(2017, 1, 1)) // winter on northern hemisphere (possible DST on southern hemisphere) .addRoundTrip(dateDataType(), dateOfLocalTimeChangeForwardAtMidnightInJvmZone) .addRoundTrip(dateDataType(), dateOfLocalTimeChangeForwardAtMidnightInSomeZone) .addRoundTrip(dateDataType(), dateOfLocalTimeChangeBackwardAtMidnightInSomeZone); for (String timeZoneId : ImmutableList.of(UTC_KEY.getId(), jvmZone.getId(), someZone.getId())) { Session session = Session.builder(getQueryRunner().getDefaultSession()) .setTimeZoneKey(TimeZoneKey.getTimeZoneKey(timeZoneId)) .build(); testCases.execute(getQueryRunner(), session, mysqlCreateAndInsert("tpch.test_date")); testCases.execute(getQueryRunner(), session, prestoCreateAsSelect("test_date")); } }
@Test public void testDateToTimestampCoercion() { // allow running tests with a connector that supports TIMESTAMP but not DATE // ordinary date MaterializedResult rows = h2QueryRunner.execute(TEST_SESSION, "SELECT DATE '2018-01-13'", ImmutableList.of(TIMESTAMP)); assertEquals(rows.getOnlyValue(), LocalDate.of(2018, 1, 13).atStartOfDay()); // date, which midnight was skipped in JVM zone LocalDate forwardOffsetChangeAtMidnightInJvmZone = LocalDate.of(1970, 1, 1); checkState(ZoneId.systemDefault().getRules().getValidOffsets(forwardOffsetChangeAtMidnightInJvmZone.atStartOfDay()).size() == 0, "This test assumes certain JVM time zone"); rows = h2QueryRunner.execute(TEST_SESSION, DateTimeFormatter.ofPattern("'SELECT DATE '''uuuu-MM-dd''").format(forwardOffsetChangeAtMidnightInJvmZone), ImmutableList.of(TIMESTAMP)); assertEquals(rows.getOnlyValue(), forwardOffsetChangeAtMidnightInJvmZone.atStartOfDay()); } }