当前位置: 首页>>代码示例>>Java>>正文


Java Duration类代码示例

本文整理汇总了Java中org.joda.time.Duration的典型用法代码示例。如果您正苦于以下问题:Java Duration类的具体用法?Java Duration怎么用?Java Duration使用的例子?那么恭喜您, 这里精选的类代码示例或许可以为您提供帮助。


Duration类属于org.joda.time包,在下文中一共展示了Duration类的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Java代码示例。

示例1: formatDuration

import org.joda.time.Duration; //导入依赖的package包/类
public static String formatDuration(long duration)
{
	// Using Joda Time
	DateTime now = new DateTime(); // Now
	DateTime plus = now.plus(new Duration(duration * 1000));

	// Define and calculate the interval of time
	Interval interval = new Interval(now.getMillis(), plus.getMillis());
	Period period = interval.toPeriod(PeriodType.time());

	// Define the period formatter for pretty printing
	String ampersand = " & ";
	PeriodFormatter pf = new PeriodFormatterBuilder().appendHours().appendSuffix(ds("hour"), ds("hours"))
		.appendSeparator(" ", ampersand).appendMinutes().appendSuffix(ds("minute"), ds("minutes"))
		.appendSeparator(ampersand).appendSeconds().appendSuffix(ds("second"), ds("seconds")).toFormatter();

	return pf.print(period).trim();
}
 
开发者ID:equella,项目名称:Equella,代码行数:19,代码来源:EchoUtils.java

示例2: parseLiveboardStop

import org.joda.time.Duration; //导入依赖的package包/类
private TrainStop parseLiveboardStop(Station stop, JSONObject item) throws JSONException {
    Station destination = stationProvider.getStationById(item.getJSONObject("stationinfo").getString("id"));

    OccupancyLevel occupancyLevel = OccupancyLevel.UNKNOWN;
    if (item.has("occupancy")) {
        occupancyLevel = OccupancyLevel.valueOf(item.getJSONObject("occupancy").getString("name").toUpperCase());
    }

    return new TrainStop(
            stop,
            destination,
            new TrainStub(item.getString("vehicle"), destination, item.getJSONObject("vehicleinfo").getString("@id")),
            item.getString("platform"),
            item.getJSONObject("platforminfo").getInt("normal") == 1,
            timestamp2date(item.getString("time")),
            new Duration(item.getInt("delay") * 1000),
            item.getInt("canceled") != 0,
            (item.has("left")) && (item.getInt("left") == 1),
            item.getString("departureConnection"),
            occupancyLevel
    );
}
 
开发者ID:hyperrail,项目名称:hyperrail-for-android,代码行数:23,代码来源:IrailApiParser.java

示例3: calculateDuration

import org.joda.time.Duration; //导入依赖的package包/类
/**
 * 
 * @param date1 first event date
 * @param date2 second event date
 * @param unit time unit
 * @return duration duration (default millisecond)
 */
private long calculateDuration(DateTime date1, DateTime date2, TimeUnit unit){
	
	if (unit == TimeUnit.SECONDS) {
		return Math.abs(new Duration(date1, date2).getStandardSeconds());
	}
	else if (unit == TimeUnit.MINUTES) {
		return Math.abs(new Duration(date1, date2).getStandardMinutes());
	}
	else if (unit == TimeUnit.HOURS) {
		return Math.abs(new Duration(date1, date2).getStandardHours());
	}
	else if (unit == TimeUnit.DAYS) {
		return Math.abs(new Duration(date1, date2).getStandardDays());
	}
	
	return 0;
}
 
开发者ID:hamdikavak,项目名称:human-mobility-modeling-utilities,代码行数:25,代码来源:LocationReport.java

示例4: setUp

import org.joda.time.Duration; //导入依赖的package包/类
@Before
public void setUp() throws ComponentInitializationException {
    // Note: the private key and the encrypting credential need to be from the same keypair
    PrivateKey privateKey = new PrivateKeyStoreFactory().create(TestEntityIds.TEST_RP).getEncryptionPrivateKeys().get(0);
    encryptionCredentialFactory = new TestCredentialFactory(TEST_RP_PUBLIC_ENCRYPTION_CERT, TEST_RP_PRIVATE_ENCRYPTION_KEY);
    testRpSigningCredential = new TestCredentialFactory(TEST_RP_PUBLIC_SIGNING_CERT, TEST_RP_PRIVATE_SIGNING_KEY).getSigningCredential();

    hubMetadataResolver = mock(MetadataResolver.class);

    ResponseFactory responseFactory = new ResponseFactory(privateKey, privateKey);
    DateTimeComparator dateTimeComparator = new DateTimeComparator(Duration.standardSeconds(5));
    TimeRestrictionValidator timeRestrictionValidator = new TimeRestrictionValidator(dateTimeComparator);

    SamlAssertionsSignatureValidator samlAssertionsSignatureValidator = mock(SamlAssertionsSignatureValidator.class);
    InstantValidator instantValidator = new InstantValidator(dateTimeComparator);
    SubjectValidator subjectValidator = new SubjectValidator(timeRestrictionValidator);
    ConditionsValidator conditionsValidator = new ConditionsValidator(timeRestrictionValidator, new AudienceRestrictionValidator());
    AssertionValidator assertionValidator = new AssertionValidator(instantValidator, subjectValidator, conditionsValidator);
    AssertionTranslator assertionTranslator = new AssertionTranslator(samlAssertionsSignatureValidator, assertionValidator);

    responseService = responseFactory.createResponseService(
        hubMetadataResolver,
        assertionTranslator,
        dateTimeComparator
    );
}
 
开发者ID:alphagov,项目名称:verify-service-provider,代码行数:27,代码来源:ResponseServiceTest.java

示例5: Transfer

import org.joda.time.Duration; //导入依赖的package包/类
public Transfer(Station station, TrainStub arrivingTrain, TrainStub departingTrain, String arrivalPlatform, boolean arrivalNormal, boolean arrived, boolean departureNormal, boolean left, String departurePlatform, Duration arrivalDelay, boolean arrivalCanceled, Duration departureDelay, boolean departureCanceled, DateTime arrivalTime, DateTime departureTime, String departureConnectionSemanticId, OccupancyLevel departureOccupancy) {
    this.station = station;
    this.arrivingTrain = arrivingTrain;
    this.departingTrain = departingTrain;
    this.arrived = arrived;
    this.left = left;
    this.arrivalTime = arrivalTime;
    this.departureTime = departureTime;
    this.departurePlatform = departurePlatform;
    this.arrivalPlatform = arrivalPlatform;
    this.arrivalDelay = arrivalDelay;
    this.departureDelay = departureDelay;
    this.arrivalCanceled = arrivalCanceled;
    this.departureCanceled = departureCanceled;
    this.isDeparturePlatformNormal = departureNormal;
    this.isArrivalPlatformNormal = arrivalNormal;
    this.departureConnectionSemanticId = departureConnectionSemanticId;
    this.departureOccupancy = departureOccupancy;
}
 
开发者ID:hyperrail,项目名称:hyperrail-for-android,代码行数:20,代码来源:Transfer.java

示例6: setUp

import org.joda.time.Duration; //导入依赖的package包/类
@Before
public void setUp() throws Exception {
    validator = new EidasAttributeQueryValidator(
        verifyMetadataResolver,
        countryMetadataResolver,
        verifyCertificateValidator,
        countryCertificateValidator,
        certificateExtractor,
        x509CertificateFactory,
        new DateTimeComparator(Duration.ZERO),
        assertionDecrypter,
        HUB_CONNECTOR_ENTITY_ID);

    when(verifyMetadataResolver.resolveSingle(any(CriteriaSet.class))).thenReturn(entityDescriptor);
    when(countryMetadataResolver.resolveSingle(any(CriteriaSet.class))).thenReturn((entityDescriptor));
    when(certificateExtractor.extractHubSigningCertificates(entityDescriptor))
        .thenReturn(Arrays.asList(new Certificate(HUB_ENTITY_ID, TestCertificateStrings.HUB_TEST_PUBLIC_SIGNING_CERT, Certificate.KeyUse.Signing)));
    when(certificateExtractor.extractIdpSigningCertificates(entityDescriptor))
        .thenReturn(Arrays.asList(new Certificate(TEST_ENTITY_ID, TestCertificateStrings.TEST_PUBLIC_CERT, Certificate.KeyUse.Signing)));
}
 
开发者ID:alphagov,项目名称:verify-matching-service-adapter,代码行数:21,代码来源:EidasAttributeQueryValidatorTest.java

示例7: getExpiryStatus

import org.joda.time.Duration; //导入依赖的package包/类
public CertificateExpiryStatus getExpiryStatus(Duration warningPeriod) {
    try {
        Date notAfter = getNotAfter();
        LocalDateTime now = LocalDateTime.now();
        Date notBefore = getNotBefore();
        if (now.toDate().after(notAfter) || now.toDate().before(notBefore)) {
            return CertificateExpiryStatus.CRITICAL;
        }
        if (now.plus(warningPeriod).toDate().after(notAfter)) {
            return CertificateExpiryStatus.WARNING;
        }
        return CertificateExpiryStatus.OK;
    } catch (CertificateException e) {
        return CertificateExpiryStatus.CRITICAL;
    }
}
 
开发者ID:alphagov,项目名称:verify-hub,代码行数:17,代码来源:Certificate.java

示例8: main

import org.joda.time.Duration; //导入依赖的package包/类
/** Run a batch or streaming pipeline. */
public static void main(String[] args) throws Exception {
  Options options = PipelineOptionsFactory.fromArgs(args).withValidation().as(Options.class);

  Pipeline pipeline = Pipeline.create(options);

  TableReference tableRef = new TableReference();
  tableRef.setDatasetId(options.as(Options.class).getOutputDataset());
  tableRef.setProjectId(options.as(GcpOptions.class).getProject());
  tableRef.setTableId(options.getOutputTableName());

  // Read events from either a CSV file or PubSub stream.
  pipeline
      .apply(new ReadGameEvents(options))
      .apply("WindowedTeamScore", new Exercise2.WindowedTeamScore(Duration.standardMinutes(60)))
      // Write the results to BigQuery.
      .apply(ParDo.named("FormatTeamScoreSums").of(new Exercise2.FormatTeamScoreSumsFn()))
      .apply(
          BigQueryIO.Write.to(tableRef)
              .withSchema(Exercise2.FormatTeamScoreSumsFn.getSchema())
              .withCreateDisposition(CreateDisposition.CREATE_IF_NEEDED)
              .withWriteDisposition(WriteDisposition.WRITE_APPEND));

  pipeline.run();
}
 
开发者ID:mdvorsky,项目名称:DataflowSME,代码行数:26,代码来源:Exercise3.java

示例9: Route

import org.joda.time.Duration; //导入依赖的package包/类
Route(Station departureStation, Station arrivalStation, DateTime departureTime, Duration departureDelay, String departurePlatform, boolean isDeparturePlatformNormal, DateTime arrivalTime, Duration arrivalDelay, String arrivalPlatform, boolean isArrivalDeparturePlatformNormal, TrainStub[] trains, Transfer[] transfers, Message[] alerts, Message[][] trainalerts, Message[] remarks) {
    this.departureStation = departureStation;
    this.arrivalStation = arrivalStation;

    this.departureTime = departureTime;
    this.departureDelay = departureDelay;
    this.isDeparturePlatformNormal = isDeparturePlatformNormal;
    this.arrivalTime = arrivalTime;
    this.arrivalDelay = arrivalDelay;

    this.departurePlatform = departurePlatform;
    this.arrivalPlatform = arrivalPlatform;

    this.isArrivalDeparturePlatformNormal = isArrivalDeparturePlatformNormal;
    this.trains = trains;
    this.transfers = transfers;
    this.alerts = alerts;
    this.trainalerts = trainalerts;
    this.remarks = remarks;
}
 
开发者ID:hyperrail,项目名称:hyperrail-for-android,代码行数:21,代码来源:Route.java

示例10: parseTrainStop

import org.joda.time.Duration; //导入依赖的package包/类
private TrainStop parseTrainStop(Station destination, TrainStub t, JSONObject item) throws JSONException {
    Station stop = stationProvider.getStationById(item.getJSONObject("stationinfo").getString("id"));

    OccupancyLevel occupancyLevel = OccupancyLevel.UNKNOWN;
    if (item.has("occupancy")) {
        occupancyLevel = OccupancyLevel.valueOf(item.getJSONObject("occupancy").getString("name").toUpperCase());
    }

    return new TrainStop(
            stop,
            destination,
            t,
            item.getString("platform"),
            item.getJSONObject("platforminfo").getInt("normal") == 1,
            timestamp2date(item.getString("scheduledDepartureTime")),
            timestamp2date(item.getString("scheduledArrivalTime")),
            new Duration(item.getInt("departureDelay") * 1000),
            new Duration(item.getInt("arrivalDelay") * 1000),
            item.getInt("departureCanceled") != 0,
            item.getInt("arrivalCanceled") != 0,
            item.getInt("left") == 1,
            item.getString("departureConnection"),
            occupancyLevel
    );
}
 
开发者ID:hyperrail,项目名称:hyperrail-for-android,代码行数:26,代码来源:IrailApiParser.java

示例11: createActiveDirectoryApplication

import org.joda.time.Duration; //导入依赖的package包/类
private static ActiveDirectoryApplication createActiveDirectoryApplication(Azure.Authenticated authenticated) throws Exception {
    String name = SdkContext.randomResourceName("adapp-sample", 20);
    //create a self-sighed certificate
    String domainName = name + ".com";
    String certPassword = "StrongPass!12";
    Certificate certificate = Certificate.createSelfSigned(domainName, certPassword);

    // create Active Directory application
    ActiveDirectoryApplication activeDirectoryApplication = authenticated.activeDirectoryApplications()
            .define(name)
                .withSignOnUrl("https://github.com/Azure/azure-sdk-for-java/" + name)
                // password credentials definition
                .definePasswordCredential("password")
                    .withPasswordValue("[email protected]")
                    .withDuration(Duration.standardDays(700))
                    .attach()
                // certificate credentials definition
                .defineCertificateCredential("cert")
                    .withAsymmetricX509Certificate()
                    .withPublicKey(Files.readAllBytes(Paths.get(certificate.getCerPath())))
                    .withDuration(Duration.standardDays(100))
                    .attach()
                .create();
    System.out.println(activeDirectoryApplication.id() + " - " + activeDirectoryApplication.applicationId());
    return activeDirectoryApplication;
}
 
开发者ID:Azure,项目名称:azure-libraries-for-java,代码行数:27,代码来源:ManageServicePrincipal.java

示例12: timeQuantity

import org.joda.time.Duration; //导入依赖的package包/类
/**
 * Format a duration (Quantity of time) to human readable string
 *
 * @param duration   The period to format
 * @param targetUnit The target unit
 * @return A string formatted as [amount] [i18n scalar descriptor]
 */
public String timeQuantity(Duration duration, TimeUnit targetUnit) {
  switch (targetUnit) {
    case DAYS:
      long days = duration.getStandardDays();
      return days + " " + i18n.getIfElse(MathUtils.isPlural(days), TIMEUNIT_DAYS, TIMEUNIT_DAY);
    case HOURS:
      long hours = duration.getStandardHours();
      return hours + " " + i18n.getIfElse(MathUtils.isPlural(hours), TIMEUNIT_HOURS, TIMEUNIT_HOUR);
    case MINUTES:
      long minutes = duration.getStandardMinutes();
      return minutes + " " + i18n.getIfElse(MathUtils.isPlural(minutes), TIMEUNIT_MINUTES, TIMEUNIT_MINUTE);
    case SECONDS:
      long seconds = duration.getStandardSeconds();
      return seconds + " " + i18n.getIfElse(MathUtils.isPlural(seconds), TIMEUNIT_SECONDS, TIMEUNIT_SECOND);
    default:
      throw new UnsupportedOperationException("Quantifying " + targetUnit.toString() + " is not supported");
  }
}
 
开发者ID:Juraji,项目名称:Biliomi,代码行数:26,代码来源:TimeFormatter.java

示例13: pointsSettingsCommandInterval

import org.joda.time.Duration; //导入依赖的package包/类
/**
 * The sub command for setting payout intervals
 * Usage: !pointssettings interval [online|offline] [minutes (5 at minimum)]
 */
@SubCommandRoute(parentCommand = "pointssettings", command = "interval")
public boolean pointsSettingsCommandInterval(User user, Arguments arguments) {
  StreamState when = EnumUtils.toEnum(arguments.get(0), StreamState.class);
  Integer intervalMinutes = NumberConverter.asNumber(arguments.getSafe(1)).toInteger();

  if (when == null || intervalMinutes == null || intervalMinutes < 5) {
    chat.whisper(user, i18n.get("ChatCommand.pointsSettingsCommand.interval.usage"));
    return false;
  }

  Duration duration = new Duration(intervalMinutes, 60000);

  if (StreamState.ONLINE.equals(when)) {
    settings.setOnlinePayoutInterval(duration.getMillis());
  } else {
    settings.setOfflinePayoutInterval(duration.getMillis());
  }

  settingsService.save(settings);
  chat.whisper(user, i18n.get("ChatCommand.pointsSettingsCommand.interval.set")
      .add("streamstate", i18n.getStreamState(when))
      .add("interval", timeFormatter.timeQuantity(duration.getMillis())));
  return true;
}
 
开发者ID:Juraji,项目名称:Biliomi,代码行数:29,代码来源:PointsComponent.java

示例14: setUp

import org.joda.time.Duration; //导入依赖的package包/类
@Before
public void setUp() throws Exception {
    PrivateKey privateKey = new PrivateKeyStoreFactory().create(TestEntityIds.TEST_RP).getEncryptionPrivateKeys().get(0);
    ResponseFactory responseFactory = new ResponseFactory(privateKey, privateKey);

    EntityDescriptor entityDescriptor = anEntityDescriptor()
        .withIdpSsoDescriptor(anIdpSsoDescriptor()
            .addKeyDescriptor(aKeyDescriptor()
                .withX509ForSigning(TEST_RP_MS_PUBLIC_SIGNING_CERT)
                .build())
            .build())
        .build();

    MetadataResolver msaMetadataResolver = mock(MetadataResolver.class);
    DateTimeComparator dateTimeComparator = new DateTimeComparator(Duration.standardSeconds(5));
    when(msaMetadataResolver.resolve(any())).thenReturn(ImmutableList.of(entityDescriptor));

    translator = responseFactory.createAssertionTranslator(msaMetadataResolver, dateTimeComparator);
}
 
开发者ID:alphagov,项目名称:verify-service-provider,代码行数:20,代码来源:AssertionTranslatorTest.java

示例15: withInitialBackoff

import org.joda.time.Duration; //导入依赖的package包/类
/**
 * Returns a copy of this {@link FluentBackoff} that instead uses the specified initial backoff
 * duration.
 *
 * <p>Does not modify this object.
 *
 * @see FluentBackoff
 */
public FluentBackoff withInitialBackoff(Duration initialBackoff) {
  checkArgument(
      initialBackoff.isLongerThan(Duration.ZERO),
      "initialBackoff %s must be at least 1 millisecond",
      initialBackoff);
  return new FluentBackoff(
      exponent, initialBackoff, maxBackoff, maxCumulativeBackoff, maxRetries);
}
 
开发者ID:spotify,项目名称:hype,代码行数:17,代码来源:FluentBackoff.java


注:本文中的org.joda.time.Duration类示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。