org.joda.time.DateTime.minusDays()方法的使用及代码示例

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

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

DateTime.minusDays介绍

[英]Returns a copy of this datetime minus the specified number of days.

The calculation will do its best to only change the day field retaining the same time of day. However, in certain circumstances, typically daylight savings cutover, it may be necessary to alter the time fields.

In spring an hour is typically removed. If subtracting one day results in the time being within the cutover then the time is adjusted to be within summer time. For example, if the cutover is from 01:59 to 03:00 and the result of this method would have been 02:30, then the result will be adjusted to 03:30.

The following three lines are identical in effect:

DateTime subtracted = dt.minusDays(6); 
DateTime subtracted = dt.minus(Period.days(6)); 
DateTime subtracted = dt.withFieldAdded(DurationFieldType.days(), -6);

This datetime instance is immutable and unaffected by this method call.
[中]返回此datetime减去指定天数的副本。
计算将尽最大努力只更改保留当天相同时间的day字段。但是,在某些情况下,通常是夏令时切换,可能需要更改时间字段。
在春天,一个小时通常被取消。如果减去一天导致时间在切换范围内,则将时间调整为在夏季时间内。例如,如果切换时间为01:59到03:00,且此方法的结果为02:30,则结果将调整为03:30。
以下三行实际上是相同的:

DateTime subtracted = dt.minusDays(6); 
DateTime subtracted = dt.minus(Period.days(6)); 
DateTime subtracted = dt.withFieldAdded(DurationFieldType.days(), -6);

此datetime实例是不可变的,不受此方法调用的影响。

代码示例

代码示例来源:origin: stackoverflow.com

DateTime today = new DateTime();
DateTime yesterday = today.minusDays(1);

Duration duration = new Duration(yesterday, today);
System.out.println(duration.getStandardDays());
System.out.println(duration.getStandardHours());
System.out.println(duration.getStandardMinutes());

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

private DateTime getSafeFirstCatalogEffectiveDate(@Nullable final DateTime input, final CallContext callContext) {
  // The effectiveDate for the initial version does not matter too much
  // Because of #760, we want to make that client passing a approximate date (e.g today.toDateTimeAtStartOfDay()) will find the version
  final DateTime catalogEffectiveDate = callContext.getCreatedDate().minusDays(1);
  return (input == null || input.isAfter(catalogEffectiveDate)) ? catalogEffectiveDate : input;
}

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

private List<Modification> multipleModificationList() {
  List<Modification> modifications = new ArrayList<>();
  Date today = new Date();
  Date yesterday = new DateTime().minusDays(1).toDate();
  Modification modification1 = new Modification("lgao", "Fixing the not checked in files", "foo@bar.com", yesterday, "99");
  modification1.createModifiedFile("build.xml", "\\build", ModifiedAction.added);
  modifications.add(modification1);
  Modification modification2 = new Modification("committer", "Added the README file", "foo@bar.com", today, "100");
  modification2.createModifiedFile("oldbuild.xml", "\\build", ModifiedAction.added);
  modifications.add(modification2);
  Modification modification3 = new Modification("committer <html />", "Added the README file with <html />", "foo@bar.com", today, "101");
  modification3.createModifiedFile("README.txt", "\\build", ModifiedAction.added);
  modifications.add(modification3);
  return modifications;
}

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

public void createTestFileWithAge(String path, int age)
  throws Exception {
 File testFile = new File(path);
 testFile.createNewFile();
 testFile.setLastModified(DateTime.now().minusDays(age).getMillis());
}

代码示例来源:origin: stackoverflow.com

public static String formatToYesterdayOrToday(String date) {
  DateTime dateTime = DateTimeFormat.forPattern("EEE hh:mma MMM d, yyyy").parseDateTime(date);
  DateTime today = new DateTime();
  DateTime yesterday = today.minusDays(1);
  DateTimeFormatter timeFormatter = DateTimeFormat.forPattern("hh:mma");

  if (dateTime.toLocalDate().equals(today.toLocalDate())) {
    return "Today " + timeFormatter.print(dateTime);
  } else if (dateTime.toLocalDate().equals(yesterday.toLocalDate())) {
    return "Yesterday " + timeFormatter.print(dateTime);
  } else {
    return date;
  }
}

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

private void sampleGetRelativeTimeSpanString() {
  List<String> text = new ArrayList<String>();
  DateTime now = DateTime.now();
  text.add("Short future: " + DateUtils.getRelativeTimeSpanString(this, now.plusMinutes(25)));
  text.add("Medium future: " + DateUtils.getRelativeTimeSpanString(this, now.plusHours(5)));
  text.add("Long future: " + DateUtils.getRelativeTimeSpanString(this, now.plusDays(3)));
  text.add("Short past: " + DateUtils.getRelativeTimeSpanString(this, now.minusMinutes(25)));
  text.add("Medium past: " + DateUtils.getRelativeTimeSpanString(this, now.minusHours(5)));
  text.add("Long past: " + DateUtils.getRelativeTimeSpanString(this, now.minusDays(3)));
  addSample("DateUtils.getRelativeTimeSpanString()", text);
}

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

private void sampleGetRelativeDateTimeString() {
  List<String> text = new ArrayList<String>();
  DateTime now = DateTime.now();
  text.add("Short future: " + DateUtils.getRelativeDateTimeString(this, now.plusMinutes(25), null, 0));
  text.add("Medium future: " + DateUtils.getRelativeDateTimeString(this, now.plusHours(5), null, 0));
  text.add("Long future: " + DateUtils.getRelativeDateTimeString(this, now.plusDays(3), null, 0));
  text.add("Short past: " + DateUtils.getRelativeDateTimeString(this, now.minusMinutes(25), null, 0));
  text.add("Medium past: " + DateUtils.getRelativeDateTimeString(this, now.minusHours(5), null, 0));
  text.add("Long past: " + DateUtils.getRelativeDateTimeString(this, now.minusDays(3), null, 0));
  addSample("DateUtils.getRelativeDateTimeString()", text);
}

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

private void sampleGetRelativeTimeSpanStringWithPreposition() {
  List<String> text = new ArrayList<String>();
  DateTime now = DateTime.now();
  text.add("Short future: " + DateUtils.getRelativeTimeSpanString(this, now.plusMinutes(25), true));
  text.add("Medium future: " + DateUtils.getRelativeTimeSpanString(this, now.plusHours(5), true));
  text.add("Long future: " + DateUtils.getRelativeTimeSpanString(this, now.plusDays(3), true));
  text.add("Short past: " + DateUtils.getRelativeTimeSpanString(this, now.minusMinutes(25), true));
  text.add("Medium past: " + DateUtils.getRelativeTimeSpanString(this, now.minusHours(5), true));
  text.add("Long past: " + DateUtils.getRelativeTimeSpanString(this, now.minusDays(3), true));
  addSample("DateUtils.getRelativeTimeSpanString() (with preposition)", text);
}

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

@Test
public void testShouldReturn() {
  DateTime now = new DateTime();
  DateTime yesterday = now.minusDays(1);
  assertEquals(new TimeConverter.ConvertedTime(TimeConverter.getHumanReadableDate(now)),
      timeConverter
          .getConvertedTime(now.toDate(), yesterday.toDate()));
}

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

@Test
public void testShouldCreateWorkunitsOlderThanLookback() throws Exception {
 long currentTime = System.currentTimeMillis();
 long partitionCreateTime = new DateTime(currentTime).minusDays(35).getMillis();
 org.apache.hadoop.hive.ql.metadata.Partition partition =
   this.hiveMetastoreTestUtils.createDummyPartition(partitionCreateTime);
 SourceState testState = getTestState("testDb6");
 HiveSource source = new HiveSource();
 source.initialize(testState);
 boolean isOlderThanLookback = source.isOlderThanLookback(partition);
 Assert.assertEquals(isOlderThanLookback, true, "Should not create workunits older than lookback");
}

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

@Before
public void setUp() {
  nowMod = new Modification("user3", "fixed the build.", null, new DateTime().toDate(), "100");
  nowMod.createModifiedFile("foo.java", ".", ModifiedAction.modified);
  oneHourAgoMod = new Modification("user2", "fixed the build.", null, new DateTime().minusHours(1).toDate(), "89");
  oneHourAgoMod.createModifiedFile("foo.java", ".", ModifiedAction.modified);
  yesterdayMod = new Modification("user1", "fixed the build.", null, new DateTime().minusDays(1).toDate(), "9");
  yesterdayMod.createModifiedFile("foo.java", ".", ModifiedAction.modified);
  material = MaterialsMother.svnMaterial("foo");
  material.setName(new CaseInsensitiveString("Foo"));
}

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

@Test
public void testShouldCreateWorkunitsNewerThanLookback() throws Exception {
 long currentTime = System.currentTimeMillis();
 // Default lookback time is 3 days
 long partitionCreateTime = new DateTime(currentTime).minusDays(2).getMillis();
 org.apache.hadoop.hive.ql.metadata.Partition partition =
   this.hiveMetastoreTestUtils.createDummyPartition(partitionCreateTime);
 SourceState testState = getTestState("testDb7");
 HiveSource source = new HiveSource();
 source.initialize(testState);
 boolean isOlderThanLookback = source.isOlderThanLookback(partition);
 Assert.assertEquals(isOlderThanLookback, false, "Should create workunits newer than lookback");
}

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

@Test
public void shouldReturnTheLatestStageEvenWhenThereIsANullStage() {
  Date occuredFirst = new DateTime().minusDays(1).toDate();
  Date occuredSecond = new DateTime().toDate();
  StageInstanceModels stageInstanceModels = stagePerJob("stage", job(JobResult.Passed, occuredSecond), job(JobResult.Passed, occuredFirst));
  NullStageHistoryItem stageHistoryItem = new NullStageHistoryItem("not_yet_run", false);
  stageInstanceModels.add(stageHistoryItem);
  PipelineInstanceModel instanceModel = PipelineInstanceModel.createPipeline("pipeline", -1, "label", createWithEmptyModifications(), stageInstanceModels);
  StageInstanceModel value = stageInstanceModels.get(0);
  assertThat(instanceModel.latestStage(), is(value));
}

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

@Test
public void shouldReturnIfAStageIsLatest() {
  Date occuredFirst = new DateTime().minusDays(1).toDate();
  Date occuredSecond = new DateTime().toDate();
  StageInstanceModels stageInstanceModels = stagePerJob("stage", job(JobResult.Passed, occuredSecond), job(JobResult.Passed, occuredFirst));
  NullStageHistoryItem stageHistoryItem = new NullStageHistoryItem("not_yet_run", false);
  stageInstanceModels.add(stageHistoryItem);
  PipelineInstanceModel instanceModel = PipelineInstanceModel.createPipeline("pipeline", -1, "label", createWithEmptyModifications(), stageInstanceModels);
  assertThat(instanceModel.isLatestStage(stageInstanceModels.get(0)), is(true));
  assertThat(instanceModel.isLatestStage(stageInstanceModels.get(1)), is(false));
}

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

@Test
public void shouldClearAgentAssignment_ForSingleInstanceJobType() {
  Date old = new DateTime().minusDays(2).toDate();
  JobInstance rails = jobInstance(old, "rails", 7, 10);
  JobInstance java = jobInstance(old, "java", 12, 22);
  Stage stage = stage(9, rails, java);
  Stage newStage = instanceFactory.createStageForRerunOfJobs(stage, a("rails"), new DefaultSchedulingContext("loser", new Agents()), StageConfigMother.custom("dev", "rails", "java"),
      new TimeProvider(), "md5");
  assertThat(newStage.getJobInstances().getByName("rails").getAgentUuid(), is(nullValue()));
  assertThat(newStage.getJobInstances().getByName("java").getAgentUuid(), is(not(nullValue())));
}

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

@Test
public void testAppliesToAll()
{
 DateTime now = DateTimes.of("2012-12-31T01:00:00");
 PeriodDropRule rule = new PeriodDropRule(
   new Period("P5000Y"),
   false
 );
 Assert.assertTrue(
   rule.appliesTo(
     builder.interval(
       new Interval(
         now.minusDays(2),
         now.minusDays(1)
       )
     ).build(),
     now
   )
 );
 Assert.assertTrue(
   rule.appliesTo(
     builder.interval(new Interval(now.minusYears(100), now.minusDays(1)))
           .build(),
     now
   )
 );
}

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

@Test
public void shouldNotRerun_WhenJobConfigDoesNotExistAnymore_ForSingleInstanceJob() {
  Date old = new DateTime().minusDays(2).toDate();
  JobInstance rails = jobInstance(old, "rails", 7, 10);
  JobInstance java = jobInstance(old, "java", 12, 22);
  Stage stage = stage(9, rails, java);
  Stage newStage = null;
  CannotRerunJobException exception = null;
  try {
    newStage = instanceFactory.createStageForRerunOfJobs(stage, a("rails"), new DefaultSchedulingContext("loser", new Agents()), StageConfigMother.custom("dev", "java"), new TimeProvider(),
        "md5");
    fail("should not schedule when job config does not exist anymore");
  } catch (CannotRerunJobException e) {
    exception = e;
  }
  assertThat(exception.getJobName(), is("rails"));
  assertThat(newStage, is(nullValue()));
}

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

@Test
public void testAppliesToPeriod()
{
 DateTime now = DateTimes.of("2012-12-31T01:00:00");
 PeriodLoadRule rule = new PeriodLoadRule(
   new Period("P1M"),
   false,
   ImmutableMap.of("", 0)
 );
 Assert.assertTrue(rule.appliesTo(builder.interval(new Interval(now.minusWeeks(1), now)).build(), now));
 Assert.assertTrue(
   rule.appliesTo(
     builder.interval(new Interval(now.minusDays(1), now.plusDays(1)))
         .build(),
     now
   )
 );
 Assert.assertFalse(
   rule.appliesTo(
     builder.interval(new Interval(now.plusDays(1), now.plusDays(2)))
           .build(),
     now
   )
 );
}

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

@Test
public void shouldNotRerun_WhenJobConfigIsChangedToRunMultipleInstance_ForSingleJobInstance() {
  Date old = new DateTime().minusDays(2).toDate();
  StageConfig stageConfig = StageConfigMother.custom("dev", "rails", "java");
  JobConfig railsConfig = stageConfig.getJobs().getJob(new CaseInsensitiveString("rails"));
  DefaultSchedulingContext schedulingContext = new DefaultSchedulingContext("loser", new Agents());
  JobInstances jobs = instanceFactory.createJobInstance(new CaseInsensitiveString("dev"), railsConfig, schedulingContext, new TimeProvider(), null);
  Stage stage = createStageInstance(old, jobs);
  Stage newStage = null;
  railsConfig.setRunInstanceCount(10);
  CannotRerunJobException exception = null;
  try {
    newStage = instanceFactory.createStageForRerunOfJobs(stage, a("rails"), schedulingContext, stageConfig, new TimeProvider(), "md5");
    fail("should not schedule since job config changed to run multiple instance");
  } catch (CannotRerunJobException e) {
    exception = e;
  }
  assertThat(exception.getJobName(), is("rails"));
  assertThat(exception.getInformation(), is("Run configuration for job has been changed to 'run multiple instance'."));
  assertThat(newStage, is(nullValue()));
}

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

@Test
public void shouldClear_DatabaseIds_State_and_Result_ForJobObjectHierarchy() {
  Date old = new DateTime().minusDays(2).toDate();
  JobInstance rails = jobInstance(old, "rails", 7, 10);
  JobInstance java = jobInstance(old, "java", 12, 22);
  Stage stage = stage(9, rails, java);
  assertThat(stage.hasRerunJobs(), is(false));
  Stage newStage = instanceFactory.createStageForRerunOfJobs(stage, a("rails"), new DefaultSchedulingContext("loser", new Agents()), StageConfigMother.custom("dev", "rails", "java"),
      new TimeProvider(), "md5");
  assertThat(stage.hasRerunJobs(), is(false));
  assertThat(newStage.getId(), is(-1l));
  assertThat(newStage.getJobInstances().size(), is(2));
  assertThat(newStage.isLatestRun(), is(true));
  JobInstance newRails = newStage.getJobInstances().getByName("rails");
  assertNewJob(old, newRails);
  JobInstance newJava = newStage.getJobInstances().getByName("java");
  assertCopiedJob(newJava, 12l);
}

相关文章

DateTime类方法