/** * Returns the current time in yyMMdd-hhmmss format. */ public static String yyMMdd_hhmmss() { return DateTimeFormat.forPattern("yyMMdd-hhmmss").print(new DateTime()); } }
private static Date parseDatetime(String dateStr) { Date date = null; int len = dateStr.length(); if (len == 10 && dateStr.charAt(4) == '-' && dateStr.charAt(7) == '-') { date = new DateTime(dateStr).toDate(); } else if (len == 8 && dateStr.charAt(2) == ':' && dateStr.charAt(5) == ':') { date = new DateTime("T" + dateStr).toDate(); } else if (len >= 19 && dateStr.charAt(4) == '-' && dateStr.charAt(7) == '-' && dateStr.charAt(13) == ':' && dateStr.charAt(16) == ':') { date = new DateTime(dateStr.replace(" ", "T")).toDate(); } return date; } }
/** * Returns a copy of this datetime with the month of year field updated. * <p> * DateTime is immutable, so there are no set methods. * Instead, this method returns a new instance with the value of * month of year changed. * * @param monthOfYear the month of year to set * @return a copy of this object with the field set * @throws IllegalArgumentException if the value is invalid * @since 1.3 */ public DateTime withMonthOfYear(int monthOfYear) { return withMillis(getChronology().monthOfYear().set(getMillis(), monthOfYear)); }
/** * Returns a copy of this datetime with the year field updated. * <p> * DateTime is immutable, so there are no set methods. * Instead, this method returns a new instance with the value of * year changed. * * @param year the year to set * @return a copy of this object with the field set * @throws IllegalArgumentException if the value is invalid * @since 1.3 */ public DateTime withYear(int year) { return withMillis(getChronology().year().set(getMillis(), year)); }
/** * Returns a copy of this datetime with the day of week field updated. * <p> * DateTime is immutable, so there are no set methods. * Instead, this method returns a new instance with the value of * day of week changed. * * @param dayOfWeek the day of week to set * @return a copy of this object with the field set * @throws IllegalArgumentException if the value is invalid * @since 1.3 */ public DateTime withDayOfWeek(int dayOfWeek) { return withMillis(getChronology().dayOfWeek().set(getMillis(), dayOfWeek)); }
@Test public void testCastToTimeWithTimeZone() { assertFunction("cast(TIME '03:04:05.321' as time with time zone)", TIME_WITH_TIME_ZONE, new SqlTimeWithTimeZone(new DateTime(1970, 1, 1, 3, 4, 5, 321, DATE_TIME_ZONE).getMillis(), DATE_TIME_ZONE.toTimeZone())); }
@Test(groups = "fast") public void testLoadCatalogFromInsideResourceFolder() throws CatalogApiException { final DefaultVersionedCatalog c = loader.loadDefaultCatalog("com/acme/SpyCarCustom.xml"); Assert.assertEquals(c.getVersions().size(), 1); final DateTime dt = new DateTime("2015-10-04T00:00:00+00:00"); Assert.assertEquals(c.getEffectiveDate(), dt.toDate()); Assert.assertEquals(c.getCatalogName(), "SpyCarCustom"); }
@Test public void testSetTimeZoneId() throws Exception { TimeZoneKey defaultZoneKey = TimeZoneKey.getTimeZoneKey(TimeZone.getDefault().getID()); DateTimeZone defaultZone = DateTimeZone.forTimeZone(TimeZone.getDefault()); String sql = "SELECT current_timezone() zone, TIMESTAMP '2001-02-03 3:04:05' ts"; try (Connection connection = createConnection()) { try (Statement statement = connection.createStatement(); ResultSet rs = statement.executeQuery(sql)) { assertTrue(rs.next()); assertEquals(rs.getString("zone"), defaultZoneKey.getId()); assertEquals(rs.getTimestamp("ts"), new Timestamp(new DateTime(2001, 2, 3, 3, 4, 5, defaultZone).getMillis())); } connection.unwrap(PrestoConnection.class).setTimeZoneId("UTC"); try (Statement statement = connection.createStatement(); ResultSet rs = statement.executeQuery(sql)) { assertTrue(rs.next()); assertEquals(rs.getString("zone"), "UTC"); assertEquals(rs.getTimestamp("ts"), new Timestamp(new DateTime(2001, 2, 3, 3, 4, 5, DateTimeZone.UTC).getMillis())); } } }
@Test(groups = "slow", enabled = false) public void testWithGMTMinus20() throws SQLException { final LocalDate date1_1 = new LocalDate(2014, 10, 1, GregorianChronology.getInstance(DATE_TZ_MINUS_20_GMT)); // We chose a time such that it moves to next day final DateTime date2_1 = new DateTime(2014, 10, 1, 16, 48, 56, DATE_TZ_MINUS_20_GMT); insertData(date1_1, date2_1, date2_1); final FullOfDates result = readData(); assertEquals(result.getDate1().compareTo(date1_1), 0); assertEquals(result.getDate2().compareTo(date2_1), 0); assertEquals(result.getDate2().getZone().toString(), "UTC"); }
@Test(groups = "slow", expectedExceptions = InvoiceApiException.class, expectedExceptionsMessageRegExp = ".* does not have a Parent Account associated") public void testParentInvoiceTransferCreditAccountNoParent() throws Exception { final int billingDay = 14; final DateTime initialCreationDate = new DateTime(2014, 5, 15, 0, 0, 0, 0, testTimeZone); // set clock to the initial start date clock.setTime(initialCreationDate); final Account account = createAccountWithNonOsgiPaymentMethod(getChildAccountData(billingDay, null, true)); BigDecimal childAccountCBA = invoiceUserApi.getAccountCBA(account.getId(), callContext); assertEquals(childAccountCBA.compareTo(BigDecimal.ZERO), 0); invoiceUserApi.transferChildCreditToParent(account.getId(), callContext); }
@Test public void testDate() throws Exception { Date expected = new Date(new DateTime(2001, 2, 3, 4, 5, 6, DateTimeZone.UTC).getMillis()); AccumuloRowSerializer serializer = serializerClass.getConstructor().newInstance(); byte[] data = serializer.encode(DATE, expected); deserializeData(serializer, data); Date actual = serializer.getDate(COLUMN_NAME); // Convert milliseconds to days so they can be compared regardless of the time of day assertEquals(MILLISECONDS.toDays(actual.getTime()), MILLISECONDS.toDays(expected.getTime())); }
@Test(groups = "slow") public void testCancelSubscription_START_OF_TERM() throws SubscriptionBaseApiException { // Set date in such a way that Phase align with the first of the month (and so matches our hardcoded accountData account BCD) final DateTime testStartDate = new DateTime(2016, 11, 1, 0, 3, 42, 0); clock.setDeltaFromReality(testStartDate.getMillis() - clock.getUTCNow().getMillis()); final String prod = "Shotgun"; final BillingPeriod term = BillingPeriod.MONTHLY; final String planSet = PriceListSet.DEFAULT_PRICELIST_NAME; // CREATE DefaultSubscriptionBase subscription = testUtil.createSubscription(bundle, prod, term, planSet); PlanPhase currentPhase = subscription.getCurrentPhase(); assertEquals(currentPhase.getPhaseType(), PhaseType.TRIAL); // Move out of TRIAL testListener.pushExpectedEvent(NextEvent.PHASE); clock.addDays(30); assertListenerStatus(); // Artificially set the CTD final Duration ctd = testUtil.getDurationMonth(1); final DateTime newChargedThroughDate = TestSubscriptionHelper.addDuration(clock.getUTCNow(), ctd); subscriptionInternalApi.setChargedThroughDate(subscription.getId(), newChargedThroughDate, internalCallContext); subscription = (DefaultSubscriptionBase) subscriptionInternalApi.getSubscriptionFromId(subscription.getId(), internalCallContext); // Move ahead a bit abd cancel START_OF_TERM clock.addDays(5); testListener.pushExpectedEvent(NextEvent.CANCEL); subscription.cancelWithPolicy(BillingActionPolicy.START_OF_TERM, callContext); assertListenerStatus(); subscription = (DefaultSubscriptionBase) subscriptionInternalApi.getSubscriptionFromId(subscription.getId(), internalCallContext); Assert.assertEquals(subscription.getAllTransitions().get(subscription.getAllTransitions().size() - 1).getTransitionType(), SubscriptionBaseTransitionType.CANCEL); Assert.assertEquals(new LocalDate(subscription.getAllTransitions().get(subscription.getAllTransitions().size() - 1).getEffectiveTransitionTime(), accountData.getTimeZone()), new LocalDate(2016, 12, 1)); }
@Test(groups = "fast", description="Test Account event serialization") public void testAccountCreationEvent() throws Exception { final DefaultAccountData data = new DefaultAccountData("dsfdsf", "bobo", 3, "bobo@yahoo.com", 12, "USD", null, false, UUID.randomUUID(), new DateTime().toString(), "UTC", "US", "21 avenue", "", "Gling", "San Franciso", "CA", "94110", "USA", "4126789887", "notes", false); final DefaultAccountCreationEvent e = new DefaultAccountCreationEvent(data, UUID.randomUUID(), 1L, 2L, null); final String json = mapper.writeValueAsString(e); final DefaultAccountCreationEvent obj = mapper.readValue(json, DefaultAccountCreationEvent.class); Assert.assertTrue(obj.equals(e)); } }
@Test public void testParseHiveTimestamp() { DateTime time = new DateTime(2011, 5, 6, 7, 8, 9, 123, nonDefaultTimeZone()); assertEquals(parse(time, "yyyy-MM-dd HH:mm:ss"), unixTime(time, 0)); assertEquals(parse(time, "yyyy-MM-dd HH:mm:ss.S"), unixTime(time, 1)); assertEquals(parse(time, "yyyy-MM-dd HH:mm:ss.SSS"), unixTime(time, 3)); assertEquals(parse(time, "yyyy-MM-dd HH:mm:ss.SSSSSSS"), unixTime(time, 6)); assertEquals(parse(time, "yyyy-MM-dd HH:mm:ss.SSSSSSSSS"), unixTime(time, 7)); }
@Test public void testFromUnixTime() { DateTime dateTime = new DateTime(2001, 1, 22, 3, 4, 5, 0, DATE_TIME_ZONE); double seconds = dateTime.getMillis() / 1000.0; assertFunction("from_unixtime(" + seconds + ")", TimestampType.TIMESTAMP, sqlTimestampOf(dateTime, session)); dateTime = new DateTime(2001, 1, 22, 3, 4, 5, 888, DATE_TIME_ZONE); seconds = dateTime.getMillis() / 1000.0; assertFunction("from_unixtime(" + seconds + ")", TimestampType.TIMESTAMP, sqlTimestampOf(dateTime, session)); }
@Test(groups = "fast") public void testWithAccountInUtcPlus5() throws AccountApiException, EntitlementApiException { final LocalDate inputDate = new LocalDate(2013, 8, 7); clock.setDay(inputDate.plusDays(1)); final DateTimeZone timeZoneUtcPlus5 = DateTimeZone.forOffsetHours(+5); // We also use a reference time of 20, 28, 10, 0 -> DateTime in accountTimeZone will be (2013, 8, 7, 20, 28, 10) final DateTime referenceDateTime = new DateTime(2013, 1, 1, 20, 28, 10, 0, DateTimeZone.UTC); createAccount(timeZoneUtcPlus5, referenceDateTime); final DateTime targetDate = dateHelper.fromLocalDateAndReferenceTime(inputDate, clock.getUTCNow(), internalCallContext); // Things to verify: // 1. Verify the resulting DateTime brings us back into the correct LocalDate (in the account timezone) Assert.assertEquals(new LocalDate(targetDate, timeZoneUtcPlus5), inputDate); // 2. Verify the resulting DateTime has the same reference time as we indicated (in UTC) Assert.assertEquals(targetDate.toLocalTime(), referenceDateTime.toLocalTime()); // // To be more specific, we should find a UTC Date, with the exact specified reference time, and with a LocalDate one day // ahead because of the 8 hours difference. // Assert.assertEquals(targetDate, new DateTime(2013, 8, 6, 20, 28, 10, 0, DateTimeZone.UTC)); }
@Test(groups = "fast") public void testWithAccountInUtc() throws AccountApiException, EntitlementApiException { final LocalDate initialDate = new LocalDate(2013, 8, 7); clock.setDay(initialDate.plusDays(1)); final DateTime referenceDateTime = new DateTime(2013, 1, 1, 15, 43, 25, 0, DateTimeZone.UTC); createAccount(DateTimeZone.UTC, referenceDateTime); final DateTime targetDate = dateHelper.fromLocalDateAndReferenceTime(initialDate, clock.getUTCNow(), internalCallContext); final DateTime expectedDate = new DateTime(2013, 8, 7, 15, 43, 25, 0, DateTimeZone.UTC); Assert.assertEquals(targetDate, expectedDate); }
@Test(groups = "slow") public void testAccountBalanceWithNoInvoiceItems() throws EntityPersistenceException { final UUID accountId = account.getId(); final LocalDate targetDate1 = new LocalDate(2011, 10, 6); final Invoice invoice1 = new DefaultInvoice(accountId, clock.getUTCToday(), targetDate1, Currency.USD); invoiceUtil.createInvoice(invoice1, context); final BigDecimal payment1 = new BigDecimal("48.0"); final InvoicePayment payment = new DefaultInvoicePayment(InvoicePaymentType.ATTEMPT, UUID.randomUUID(), invoice1.getId(), new DateTime(), payment1, Currency.USD, Currency.USD, null, true); invoiceUtil.createPayment(payment, context); final BigDecimal balance = invoiceDao.getAccountBalance(accountId, context); assertEquals(balance.compareTo(BigDecimal.ZERO.subtract(payment1)), 0); }
@Test(groups = "fast") public void testIsBeforeOrEqualsToday() throws AccountApiException { clock.setTime(new DateTime(2013, 8, 7, 3, 28, 10, 0, DateTimeZone.UTC)); final DateTimeZone timeZoneUtcMinus8 = DateTimeZone.forOffsetHours(-8); createAccount(timeZoneUtcMinus8, clock.getUTCNow()); final DateTime inputDateEquals = new DateTime(2013, 8, 6, 23, 28, 10, 0, timeZoneUtcMinus8); // Check that our input date is greater than now assertTrue(inputDateEquals.compareTo(clock.getUTCNow()) > 0); // And yet since the LocalDate match the function returns true assertTrue(isBeforeOrEqualsToday(inputDateEquals, timeZoneUtcMinus8, internalCallContext)); }