org.joda.time.DateTime类的使用及代码示例

x33g5p2x  于2022-01-17 转载在 其他  
字(14.6k)|赞(0)|评价(0)|浏览(251)

本文整理了Java中org.joda.time.DateTime类的一些代码示例,展示了DateTime类的具体用法。这些代码示例主要来源于Github/Stackoverflow/Maven等平台,是从一些精选项目中提取出来的代码,具有较强的参考意义,能在一定程度帮忙到你。DateTime类的具体详情如下:
包路径:org.joda.time.DateTime
类名称:DateTime

DateTime介绍

[英]DateTime is the standard implementation of an unmodifiable datetime class.

DateTime is the most widely used implementation of ReadableInstant. As with all instants, it represents an exact point on the time-line, but limited to the precision of milliseconds. A DateTime calculates its fields with respect to a DateTimeZone.

Internally, the class holds two pieces of data. Firstly, it holds the datetime as milliseconds from the Java epoch of 1970-01-01T00:00:00Z. Secondly, it holds a Chronology which determines how the millisecond instant value is converted into the date time fields. The default Chronology is ISOChronology which is the agreed international standard and compatible with the modern Gregorian calendar.

Each individual field can be queried in two ways:

  • getHourOfDay()

  • hourOfDay().get()
    The second technique also provides access to other useful methods on the field:

  • numeric value

  • text value

  • short text value

  • maximum/minimum values

  • add/subtract

  • set

  • rounding

DateTime is thread-safe and immutable, provided that the Chronology is as well. All standard Chronology classes supplied are thread-safe and immutable.
[中]DateTime是不可修改的DateTime类的标准实现。
DateTime是ReadableInstant应用最广泛的实现。与所有实例一样,它表示时间线上的精确点,但精度仅限于毫秒。DateTime根据日期时区计算其字段。
在内部,该类保存两条数据。首先,它将日期时间保存为从1970-01-01T00:00:00Z的Java纪元开始的毫秒。其次,它保存一个年表,确定毫秒瞬时值如何转换为日期时间字段。默认的年表是等时法,这是商定的国际标准,与现代公历兼容。
可以通过两种方式查询每个字段:

  • getHourOfDay()
  • hourOfDay().get()
    第二种技术还提供了对现场其他有用方法的访问:
    *数值
    *文本值
    *短文本值
    *最大值/最小值
    *加减
    *设置
    *四舍五入
    DateTime是线程安全且不可变的,前提是年表也是。提供的所有标准编年史类都是线程安全且不可变的。

代码示例

代码示例来源:origin: aws/aws-sdk-java

/**
   * Returns the current time in yyMMdd-hhmmss format.
   */
  public static String yyMMdd_hhmmss() {
    return DateTimeFormat.forPattern("yyMMdd-hhmmss").print(new DateTime());
  }
}

代码示例来源:origin: apache/incubator-druid

@Override
public String apply(long value)
{
 final long truncated = granularity.bucketStart(DateTimes.utc(value)).getMillis();
 return formatter == null ? String.valueOf(truncated) : formatter.print(truncated);
}

代码示例来源:origin: alibaba/canal

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;
  }
}

代码示例来源:origin: joda-time/joda-time

/**
 * 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));
}

代码示例来源:origin: joda-time/joda-time

/**
 * 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));
}

代码示例来源:origin: joda-time/joda-time

/**
 * 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));
}

代码示例来源:origin: prestodb/presto

@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()));
}

代码示例来源:origin: killbill/killbill

@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");
}

代码示例来源:origin: prestodb/presto

@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()));
    }
  }
}

代码示例来源:origin: killbill/killbill

@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");
}

代码示例来源:origin: org.kill-bill.billing/killbill-beatrix

@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);
}

代码示例来源:origin: prestodb/presto

@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()));
}

代码示例来源:origin: killbill/killbill

@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));
}

代码示例来源:origin: killbill/killbill

@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));
  }
}

代码示例来源:origin: prestodb/presto

@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));
}

代码示例来源:origin: prestodb/presto

@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));
}

代码示例来源:origin: org.kill-bill.billing/killbill-entitlement

@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));
}

代码示例来源:origin: org.kill-bill.billing/killbill-entitlement

@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);
}

代码示例来源:origin: org.kill-bill.billing/killbill-invoice

@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);
}

代码示例来源:origin: org.kill-bill.billing/killbill-entitlement

@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));
}

相关文章

DateTime类方法