當前位置: 首頁>>代碼示例>>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;未經允許,請勿轉載。