Java 类org.joda.time.Hours 实例源码

项目:CodeWatch    文件:OnBoardActivity.java   
@SuppressLint("ApplySharedPref")
private void onSetupComplete() {
    //download whole leaderboards data asynchronously
    new FetchLeaderBoardDataAsync(this).execute();

    //schedule daily sync at 3:00 am local time
    FirebaseJobDispatcher dispatcher = new FirebaseJobDispatcher(new GooglePlayDriver(this));

    DateTime now = new DateTime();
    DateTime tomorrow = now.plusDays(1).withTimeAtStartOfDay().plusHours(3);
    int windowStart = Hours.hoursBetween(now, tomorrow).getHours() * 60 * 60;
    Job synJob = dispatcher.newJobBuilder()
            .setService(SyncScheduler.class)
            .setTag(Constants.PERIODIC_SYNC_SCHEDULE_KEY)
            .setReplaceCurrent(true)
            .setTrigger(Trigger.executionWindow(windowStart, windowStart + 10))
            .setConstraints(Constraint.ON_ANY_NETWORK)
            .setRetryStrategy(RetryStrategy.DEFAULT_LINEAR)
            .build();
    dispatcher.mustSchedule(synJob);

    sharedPreferences.edit().putBoolean(Constants.PREF_FIREBASE_SETUP, true).commit();
    startActivity(new Intent(this, PreChecksActivity.class));
    finish();
}
项目:Artificial-Intelligent-chat-bot-    文件:IntervalUtils.java   
public static int getHoursBetween(final String date1, final String date2, String format){
    try {
    final DateTimeFormatter fmt =
            DateTimeFormat
                    .forPattern(format)
                    .withChronology(
                            LenientChronology.getInstance(
                                    GregorianChronology.getInstance()));
    return Hours.hoursBetween(
            fmt.parseDateTime(date1),
            fmt.parseDateTime(date2)
    ).getHours();
    } catch (Exception ex) {
        ex.printStackTrace();
        return 0;
    }
}
项目:DSSApp    文件:DSSExport.java   
private String get_interval(DateTime largerDatetime, DateTime smallerDateTime) throws HydraClientException{
    int year_diff  = Years.yearsBetween(smallerDateTime, largerDatetime).getYears();
    int month_diff  = Months.monthsBetween(smallerDateTime, largerDatetime).getMonths();
    int day_diff  = Days.daysBetween(smallerDateTime, largerDatetime).getDays();
    int hour_diff = Hours.hoursBetween(smallerDateTime, largerDatetime).getHours();
    int min_diff  = Minutes.minutesBetween(smallerDateTime, largerDatetime).getMinutes();

    if (year_diff > 0){return year_diff+"YEAR";}
    if (month_diff > 0){return month_diff+"MONTH";}
    if (day_diff > 0){return day_diff+"DAY";}
    if (hour_diff > 0){return hour_diff+"HOUR";}
    if (min_diff > 0){return min_diff+"MIN";}

    throw new HydraClientException("Could not compute interval between times " + smallerDateTime.toString() + "and" + largerDatetime.toString());

}
项目:Rapture    文件:CronTest.java   
@Test
public void testHourRuns25TimesInDSTChangeToWinter() throws Exception {
    CronParser cron = CronParser.create("1 * * * *");
    DateTimeZone timeZone = DateTimeZone.forID("America/New_York");
    DateTime start = new DateTime(2011, 11, 6, 0, 0, 0, timeZone);
    DateTime slutt = start.plusDays(1).withTimeAtStartOfDay();
    DateTime tid = start;
    assertEquals(25, Hours.hoursBetween(start, slutt).getHours());
    int count=0;
    DateTime lastTime = tid;
    while(tid.isBefore(slutt)){
        DateTime nextTime = cron.nextRunDate(tid);
        assertTrue(nextTime.isAfter(lastTime));
        lastTime = nextTime;
        tid = tid.plusHours(1);
        count++;
    }
    assertEquals(25, count);
}
项目:Rapture    文件:CronTest.java   
@Test
public void testHourRuns23TimesInDSTChangeToSummer() throws Exception {
    CronParser cron = CronParser.create("1 * * * *");
    DateTimeZone timeZone = DateTimeZone.forID("America/New_York");
    DateTime start = new DateTime(2011, 3, 13, 0, 0, 0, timeZone);
    DateTime slutt = start.plusDays(1).withTimeAtStartOfDay();
    DateTime tid = start;
    assertEquals(23, Hours.hoursBetween(start, slutt).getHours());
    int count=0;
    DateTime lastTime = tid;
    while(tid.isBefore(slutt)){
        DateTime nextTime = cron.nextRunDate(tid);
        assertTrue(nextTime.isAfter(lastTime));
        lastTime = nextTime;
        tid = tid.plusHours(1);
        count++;
    }
    assertEquals(23, count);
}
项目:Daytripper    文件:IntervalUtils.java   
public static int getHoursBetween(final String date1, final String date2, String format){
    try {
    final DateTimeFormatter fmt =
            DateTimeFormat
                    .forPattern(format)
                    .withChronology(
                            LenientChronology.getInstance(
                                    GregorianChronology.getInstance()));
    return Hours.hoursBetween(
            fmt.parseDateTime(date1),
            fmt.parseDateTime(date2)
    ).getHours();
    } catch (Exception ex) {
        ex.printStackTrace();
        return 0;
    }
}
项目:bioforge    文件:Rules.java   
private double processEmployeeRules(List<Assignment> assignments) {
    double fitness = 0.0;
    for (Employee employee : employees) {
        List<Shift> shifts = assignments.stream()
                                        .filter(a -> a.employee.id == employee.id)
                                        .map(assignment -> assignment.shift)
                                        .collect(Collectors.toList());
        shifts.sort((a, b) -> a.start.compareTo(b.start));
        for (int i = 1; i < shifts.size(); ++i) {
            int timeBetween = Hours.hoursBetween(shifts.get(i - 1).end, shifts.get(i).start).getHours();
            if (timeBetween < restTime) {
                fitness -= HARD_SCORE;
            }
        }
        fitness += shifts.size();
    }
    return fitness;
}
项目:program-ab    文件:IntervalUtils.java   
public static int getHoursBetween(final String date1, final String date2, String format){
    try {
    final DateTimeFormatter fmt =
            DateTimeFormat
                    .forPattern(format)
                    .withChronology(
                            LenientChronology.getInstance(
                                    GregorianChronology.getInstance()));
    return Hours.hoursBetween(
            fmt.parseDateTime(date1),
            fmt.parseDateTime(date2)
    ).getHours();
    } catch (Exception ex) {
        ex.printStackTrace();
        return 0;
    }
}
项目:bigpicture    文件:HistogramDate.java   
private int computeTimeModeAndDiff(DateTime dmin, DateTime dmax) {
    int diffDay = Days.daysBetween(dmin, dmax).getDays();
    int diffHou = Hours.hoursBetween(dmin, dmax).getHours();
    int diffMin = Minutes.minutesBetween(dmin, dmax).getMinutes();
    int diffSec = Seconds.secondsBetween(dmin, dmax).getSeconds();

    int diff = diffMin;

    guessTimeMode(diffDay, diffHou, diffMin, diffSec);

    if (TimeMode.DAY.equals(timeMode)) {
        diff = diffDay;
    } else if (TimeMode.HOUR.equals(timeMode)) {
        diff = diffHou;
    } else if (TimeMode.MINUTE.equals(timeMode)) {
        diff = diffMin;
    } else if (TimeMode.SECOND.equals(timeMode)) {
        diff = diffSec;
    }

    //consoleDiffs(diffDay, diffHou, diffMin, diffSec, diff);

    return diff;
}
项目:twittererer    文件:TimelineConverter.java   
private static String dateToAge(String createdAt, DateTime now) {
    if (createdAt == null) {
        return "";
    }

    DateTimeFormatter dtf = DateTimeFormat.forPattern(DATE_TIME_FORMAT);
    try {
        DateTime created = dtf.parseDateTime(createdAt);

        if (Seconds.secondsBetween(created, now).getSeconds() < 60) {
            return Seconds.secondsBetween(created, now).getSeconds() + "s";
        } else if (Minutes.minutesBetween(created, now).getMinutes() < 60) {
            return Minutes.minutesBetween(created, now).getMinutes() + "m";
        } else if (Hours.hoursBetween(created, now).getHours() < 24) {
            return Hours.hoursBetween(created, now).getHours() + "h";
        } else {
            return Days.daysBetween(created, now).getDays() + "d";
        }
    } catch (IllegalArgumentException e) {
        return "";
    }
}
项目:java-hod-sso-spring-security    文件:UnboundTokenServiceImplTest.java   
@Test
public void getsNewUnboundToken() throws InterruptedException, HodErrorException {
    final CountDownLatch latch = new CountDownLatch(1);
    final List<Try<AuthenticationToken<EntityType.Unbound, TokenType.HmacSha1>>> outputs = Collections.synchronizedList(new ArrayList<Try<AuthenticationToken<EntityType.Unbound,TokenType.HmacSha1>>>());

    final AuthenticationToken<EntityType.Unbound, TokenType.HmacSha1> unboundToken = createToken(Hours.ONE);
    mockAuthenticateUnbound().then(new DelayedAnswer<>(unboundToken));
    mockTokenInformation(unboundToken);

    executorService.execute(new UnboundTokenGetter(unboundTokenService, outputs, latch));
    awaitLatch(latch);

    assertThat(outputs, hasSize(1));
    verify(authenticationService, times(1)).authenticateUnbound(any(ApiKey.class), eq(TokenType.HmacSha1.INSTANCE));
    checkOutput(outputs.get(0), unboundToken, null);
}
项目:java-hod-sso-spring-security    文件:UnboundTokenServiceImplTest.java   
@Test
public void getsUnboundTokenFiveTimesButOnlyFetchesOnce() throws HodErrorException, InterruptedException {
    final int times = 5;
    final CountDownLatch latch = new CountDownLatch(times);
    final List<Try<AuthenticationToken<EntityType.Unbound, TokenType.HmacSha1>>> outputs = Collections.synchronizedList(new ArrayList<Try<AuthenticationToken<EntityType.Unbound,TokenType.HmacSha1>>>());

    final AuthenticationToken<EntityType.Unbound, TokenType.HmacSha1> unboundToken = createToken(Hours.ONE);
    mockAuthenticateUnbound().then(new DelayedAnswer<>(unboundToken));
    mockTokenInformation(unboundToken);

    for (int i = 0; i < times; i++) {
        executorService.execute(new UnboundTokenGetter(unboundTokenService, outputs, latch));
    }

    awaitLatch(latch);

    assertThat(outputs, hasSize(times));
    verify(authenticationService, times(1)).authenticateUnbound(any(ApiKey.class), eq(TokenType.HmacSha1.INSTANCE));

    for (int i = 0; i < times; i++) {
        checkOutput(outputs.get(i), unboundToken, null);
    }
}
项目:java-hod-sso-spring-security    文件:UnboundTokenServiceImplTest.java   
@Test
public void getsUnboundTokenAndUUIDButOnlyFetchesOnce() throws HodErrorException, InterruptedException {
    final int times = 2;
    final CountDownLatch latch = new CountDownLatch(times);
    final List<Try<AuthenticationToken<EntityType.Unbound, TokenType.HmacSha1>>> tokenOutputs = Collections.synchronizedList(new ArrayList<Try<AuthenticationToken<EntityType.Unbound,TokenType.HmacSha1>>>());
    final List<Try<UUID>> authenticationUUIDOutputs = Collections.synchronizedList(new ArrayList<Try<UUID>>());

    final AuthenticationToken<EntityType.Unbound, TokenType.HmacSha1> unboundToken = createToken(Hours.ONE);
    mockAuthenticateUnbound().then(new DelayedAnswer<>(unboundToken));
    mockTokenInformation(unboundToken);

    executorService.execute(new UnboundTokenGetter(unboundTokenService, tokenOutputs, latch));
    executorService.execute(new UnboundAuthenticationUUIDGetter(unboundTokenService, authenticationUUIDOutputs, latch));

    awaitLatch(latch);

    assertThat(tokenOutputs, hasSize(1));
    assertThat(authenticationUUIDOutputs, hasSize(1));
    verify(authenticationService, times(1)).authenticateUnbound(any(ApiKey.class), eq(TokenType.HmacSha1.INSTANCE));

    checkOutput(tokenOutputs.get(0), unboundToken, null);
    checkOutput(authenticationUUIDOutputs.get(0), AUTH_UUID, null);
}
项目:java-hod-sso-spring-security    文件:UnboundTokenServiceImplTest.java   
@Test
public void getsUnboundTokenAfterException() throws HodErrorException, InterruptedException {
    final List<Try<AuthenticationToken<EntityType.Unbound, TokenType.HmacSha1>>> outputs = Collections.synchronizedList(new ArrayList<Try<AuthenticationToken<EntityType.Unbound,TokenType.HmacSha1>>>());
    final CountDownLatch latch = new CountDownLatch(3);

    final AuthenticationToken<EntityType.Unbound, TokenType.HmacSha1> unboundToken = createToken(Hours.ONE);
    final HodErrorException exception = createException();
    mockAuthenticateUnbound().then(new DelayedAnswer<>(exception)).then(new DelayedAnswer<>(unboundToken));
    mockTokenInformation(unboundToken);

    for (int i = 0; i < 3; i++) {
        executorService.execute(new UnboundTokenGetter(unboundTokenService, outputs, latch));
    }

    awaitLatch(latch);

    assertThat(outputs, hasSize(3));
    verify(authenticationService, times(2)).authenticateUnbound(any(ApiKey.class), eq(TokenType.HmacSha1.INSTANCE));

    checkOutput(outputs.get(0), null, exception);
    checkOutput(outputs.get(1), unboundToken, null);
    checkOutput(outputs.get(2), unboundToken, null);
}
项目:java-hod-sso-spring-security    文件:CookieHodAuthenticationProviderTest.java   
@Before
public void initialise() throws IOException, HodErrorException {
    tokenProxy = new TokenProxy<>(EntityType.Combined.INSTANCE, TokenType.Simple.INSTANCE);
    applicationAuthenticationUuid = UUID.randomUUID();

    combinedToken = new AuthenticationToken<>(
            EntityType.Combined.INSTANCE,
            TokenType.Simple.INSTANCE,
            DateTime.now().plus(Hours.TWO),
            "token-id",
            "token-secret",
            DateTime.now().plus(Hours.ONE)
    );

    when(tokenRepository.insert(combinedToken)).thenReturn(tokenProxy);
    when(unboundTokenService.getAuthenticationUuid()).thenReturn(applicationAuthenticationUuid);
}
项目:lasso    文件:MainActivity.java   
@Override
public void onReceive(Context context, Intent intent) {
    if (intent.getAction().equals(NightscoutMonitor.NEW_READING_ACTION)) {
        int uploaderBattery = Optional.fromNullable(intent.getExtras().getInt("uploaderBattery")).or(-1);
        int receiverBattery = Optional.fromNullable(intent.getExtras().getInt("receiverBattery")).or(-1);
        List<EGVRecord> egvRecords = SgvDbEntry.getLastEgvRecords(new DateTime().minus(Hours.hours(4)));
        updateView(egvRecords, uploaderBattery, receiverBattery);
    } else if (intent.getAction().equals(NightscoutMonitor.RECEIVER_STATE_INTENT)) {
        Optional<String> receiverStatus = Optional.fromNullable(intent.getExtras().getString("state"));
        if (receiverStatus.isPresent()) {
            Log.d("StateReceiver", "Received state: " + receiverStatus.get());
            if (receiverStatus.get().equals(ReceiverStatus.RECEIVER_CONNECTED.name())) {
                receiverButton.setBackgroundResource(R.drawable.ic_usb);
            } else {
                receiverButton.setBackgroundResource(R.drawable.ic_nousb);
            }
        }
    } else if (intent.getAction().equals(NightscoutMonitor.MQTT_RESPONSE_STATUS_INTENT)) {
        int res = (intent.getExtras().getBoolean(NightscoutMonitor.MQTT_STATUS_EXTRA_FIELD)) ? R.drawable.ic_cloud : R.drawable.ic_nocloud;
        uploadButton.setImageResource(res);
    }
}
项目:JDeSurvey    文件:UserService.java   
public boolean user_validateForgotPasswordKey(String hash)  {
    try {

        PasswordResetRequest  passwordResetRequest = passwordResetRequestDAO.findByHash(hash);
        if (passwordResetRequest == null) {log.info("empty return" + hash);}
        if (passwordResetRequest != null && 
            passwordResetRequest.getResetDate() == null) {
            int hours = Hours.hoursBetween(new DateTime(passwordResetRequest.getRequestDate()), new DateTime(new Date())).getHours();
            if (hours <= TIME_INTERVAL_TO_CHANGE_PASSWORD_IN_HOURS ) {
                return true;
            }
        }
        return false; 
    }
    catch (Exception e) {
        log.error(e.getMessage(),e);
        throw (new RuntimeException(e));
    }
}
项目:cron    文件:CronExpressionTest.java   
@Test
public void check_hour_shall_run_25_times_in_DST_change_to_wintertime() throws Exception {
    CronExpression cron = new CronExpression("0 1 * * * *");
    DateTime start = new DateTime(2011, 10, 30, 0, 0, 0, 0);
    DateTime slutt = start.toLocalDate().plusDays(1).toDateTimeAtStartOfDay();
    DateTime tid = start;
    assertThat(Hours.hoursBetween(start, slutt).getHours()).isEqualTo(25);
    int count=0;
    DateTime lastTime = tid;
    while(tid.isBefore(slutt)){
        DateTime nextTime = cron.nextTimeAfter(tid);
        assertThat(nextTime.isAfter(lastTime)).isTrue();
        lastTime = nextTime;
        tid = tid.plusHours(1);
        count++;
    }
    assertThat(count).isEqualTo(25);
}
项目:cron    文件:CronExpressionTest.java   
@Test
public void check_hour_shall_run_23_times_in_DST_change_to_summertime() throws Exception {
    CronExpression cron = new CronExpression("0 0 * * * *");
    DateTime start = new DateTime(2011, 03, 27, 0, 0, 0, 0);
    DateTime slutt = start.toLocalDate().plusDays(1).toDateTimeAtStartOfDay();
    DateTime tid = start;
    assertThat(Hours.hoursBetween(start, slutt).getHours()).isEqualTo(23);
    int count=0;
    DateTime lastTime = tid;
    while(tid.isBefore(slutt)){
        DateTime nextTime = cron.nextTimeAfter(tid);
        assertThat(nextTime.isAfter(lastTime)).isTrue();
        lastTime = nextTime;
        tid = tid.plusHours(1);
        count++;
    }
    assertThat(count).isEqualTo(23);
}
项目:actframework    文件:CronExpressionTest.java   
@Test
public void check_hour_shall_run_25_times_in_DST_change_to_wintertime() throws Exception {
    CronExpression cron = new CronExpression("0 1 * * * *");
    DateTime start = new DateTime(2011, 10, 30, 0, 0, 0, 0);
    DateTime slutt = start.toLocalDate().plusDays(1).toDateTimeAtStartOfDay();
    DateTime tid = start;
    assertThat(Hours.hoursBetween(start, slutt).getHours()).isEqualTo(25);
    int count=0;
    DateTime lastTime = tid;
    while(tid.isBefore(slutt)){
        DateTime nextTime = cron.nextTimeAfter(tid);
        assertThat(nextTime.isAfter(lastTime)).isTrue();
        lastTime = nextTime;
        tid = tid.plusHours(1);
        count++;
    }
    assertThat(count).isEqualTo(25);
}
项目:actframework    文件:CronExpressionTest.java   
@Test
public void check_hour_shall_run_23_times_in_DST_change_to_summertime() throws Exception {
    CronExpression cron = new CronExpression("0 0 * * * *");
    DateTime start = new DateTime(2011, 03, 27, 0, 0, 0, 0);
    DateTime slutt = start.toLocalDate().plusDays(1).toDateTimeAtStartOfDay();
    DateTime tid = start;
    assertThat(Hours.hoursBetween(start, slutt).getHours()).isEqualTo(23);
    int count=0;
    DateTime lastTime = tid;
    while(tid.isBefore(slutt)){
        DateTime nextTime = cron.nextTimeAfter(tid);
        assertThat(nextTime.isAfter(lastTime)).isTrue();
        lastTime = nextTime;
        tid = tid.plusHours(1);
        count++;
    }
    assertThat(count).isEqualTo(23);
}
项目:jfixture    文件:BaseSingleFieldPeriodRelay.java   
@Override
public Object create(Object request, SpecimenContext context) {

    if (!(request instanceof SpecimenType)) {
        return new NoSpecimen();
    }

    SpecimenType type = (SpecimenType) request;
    if (!BaseSingleFieldPeriod.class.isAssignableFrom(type.getRawType())) {
        return new NoSpecimen();
    }

    Duration duration = (Duration) context.resolve(Duration.class);
    if (type.equals(Seconds.class)) return Seconds.seconds(Math.max(1, (int) duration.getStandardSeconds()));
    if (type.equals(Minutes.class)) return Minutes.minutes(Math.max(1, (int) duration.getStandardMinutes()));
    if (type.equals(Hours.class)) return Hours.hours(Math.max(1, (int) duration.getStandardHours()));

    if (type.equals(Days.class)) return Days.days(Math.max(1, (int) duration.getStandardDays()));
    if (type.equals(Weeks.class)) return Weeks.weeks(Math.max(1, (int) duration.getStandardDays() / 7));
    if (type.equals(Months.class)) return Months.months(Math.max(1, (int) duration.getStandardDays() / 30));
    if (type.equals(Years.class)) return Years.years(Math.max(1, (int) duration.getStandardDays() / 365));

    return new NoSpecimen();
}
项目:openMAXIMS    文件:ADTImpl.java   
boolean newIpVTEAssessmentExists(PatientSummaryRecord patientSummaryRecord,Date admissionDate)
{
    try
    {
        if(patientSummaryRecord!=null
            &&admissionDate!=null
            &&patientSummaryRecord.getInpatientVTEAssessment()!=null
            &&patientSummaryRecord.getInpatientVTEAssessment().getRecordingInformation()!=null
            &&VTEAssessmentContextType.INPATIENT.getId()==(patientSummaryRecord.getInpatientVTEAssessment().getContextType().getId()))
        {
            int hours = Hours.hoursBetween(new org.joda.time.DateTime(patientSummaryRecord.getInpatientVTEAssessment().getRecordingInformation().getRecordingDateTime()),
                    new org.joda.time.DateTime(admissionDate)).getHours();
            if (Math.abs(hours)<24)
                return true;
        }
    } catch (Exception e)
    {
        LOG.error("Exception calculating if Inpatient VTE Assessment is not stale",e);
    }
    return false;
}
项目:WHNewsReader-Android    文件:MyDateUtils.java   
public static String TimeFromTodayAccuracyToTheMinute(String date){
    String Time = "";
    DateTime StoryTime = new DateTime(date);
    DateTime NowTime = new DateTime();
    int minutes = Minutes.minutesBetween(StoryTime, NowTime).getMinutes();
    int hours = Hours.hoursBetween(StoryTime, NowTime).getHours();
    int days = Days.daysBetween(StoryTime, NowTime).getDays();
    if(days > 0){
        Time  = Time + " " + days + " d";
    }
    if(BelowADay(hours) > 0){
        int timeHours = BelowADay(hours);
        Time  = Time + " " + timeHours + " h";
    }
    if(BelowAHour(minutes) > 0){
        int timeMins = BelowAHour(minutes);
        Time  = Time + " " + timeMins + " m";
    }

    Time = Time + " ago.";
    if(Time.length()==5){
        Time = "less then a minute ago.";
    }
    return Time;
}
项目:WHNewsReader-Android    文件:MyDateUtils.java   
public static String TimeFromTodayAccuracyToTheHour(String date){
    String Time = "";
    DateTime StoryTime = new DateTime(date);
    DateTime NowTime = new DateTime();
    int hours = Hours.hoursBetween(StoryTime, NowTime).getHours();
    int days = Days.daysBetween(StoryTime, NowTime).getDays();
    if(days > 0){
        Time  = Time + " " + days + " d";
    }
    if(BelowADay(hours) > 0){
        int timeHours = BelowADay(hours);
        Time  = Time + " " + timeHours + " h";
    }
    Time = Time + " ago.";
    if(Time.length()==5){
        Time = "less then a hour ago.";
    }
    return Time;
}
项目:java-util-examples    文件:CalculateDateTimeDifference.java   
@Test
public void difference_between_two_dates_joda () {

    DateTime sinceGraduation = new DateTime(1984, 6, 4, 0, 0, GregorianChronology.getInstance());
    DateTime currentDate = new DateTime(); //current date

    Days diffInDays = Days.daysBetween(sinceGraduation, currentDate);
    Hours diffInHours = Hours.hoursBetween(sinceGraduation, currentDate);
    Minutes diffInMinutes = Minutes.minutesBetween(sinceGraduation, currentDate);
    Seconds seconds = Seconds.secondsBetween(sinceGraduation, currentDate);

    logger.info(diffInDays.getDays());
    logger.info(diffInHours.getHours());
    logger.info(diffInMinutes.getMinutes());
    logger.info(seconds.getSeconds());

    assertTrue(diffInDays.getDays() >= 10697);
    assertTrue(diffInHours.getHours() >= 256747);
    assertTrue(diffInMinutes.getMinutes() >= 15404876);
    assertTrue(seconds.getSeconds() >= 924292577);

}
项目:codeine    文件:CollectionTypeGetter.java   
public List<AlertsCollectionType> getCollectionType(DateTime dateTime) {
    if (!dateTime.isAfter(lastGet)){
        throw new IllegalArgumentException("collection is not after previous " + lastGet + ", " + dateTime);
    }
    lastGet = dateTime;
    if (dateTime.getHourOfDay() >= TIME_WINDOW_TO_REPORT_DAY_MIN 
            && dateTime.getHourOfDay() <= TIME_WINDOW_TO_REPORT_DAY_MAX && 
            Hours.hoursBetween(lastDailyCollection, dateTime).getHours() > reportingWindowDay()){
        log.info("daily mail collection");
        lastDailyCollection = dateTime;
        lastHourlyCollection = dateTime;
        return Lists.newArrayList(AlertsCollectionType.Immediately, AlertsCollectionType.Hourly, AlertsCollectionType.Daily);
    }
    if (dateTime.getMinuteOfHour() <= TIME_WINDOW_TO_REPORT_HOUR && Minutes.minutesBetween(lastHourlyCollection, dateTime).getMinutes() > TIME_WINDOW_TO_REPORT_HOUR){
        log.info("hourly mail collection");
        lastHourlyCollection = dateTime;
        return Lists.newArrayList(AlertsCollectionType.Immediately, AlertsCollectionType.Hourly);
    }
    return Lists.newArrayList(AlertsCollectionType.Immediately);
}
项目:GMM    文件:BackupAccessService.java   
@Autowired
public BackupAccessService(DataConfigService config, BackupFileService service) {
    this.config = config;
    this.fileService = service;

    // timed backups
    monthlyBackup = new ConditionalBackupExecutor("monthly", 6, (now, last) -> {
            final Months duration = Months.monthsBetween(last, now);
            return duration.getMonths() >= 1;
        }
    );
    daylyBackup = new ConditionalBackupExecutor("dayly", 7, (now, last) -> {
            final Days duration = Days.daysBetween(last, now);
            return duration.getDays() >= 1;
        }
    );
    hourlyBackup = new ConditionalBackupExecutor("hourly", 24, (now, last) -> {
            final Hours duration = Hours.hoursBetween(last, now);
            return duration.getHours() >= 1;
        }
    );
    // triggered backups
    triggeredBackup = new BackupExecutor("triggered", 100);
}
项目:GowerTides    文件:Tide.java   
public String getTimeDifference(Calendar cal){

        int h_diff = Math.abs(Hours.hoursBetween(new DateTime(time.getTime()), new DateTime(cal.getTime())).getHours() % 24);
        int m_diff = Math.abs(Minutes.minutesBetween(new DateTime(time.getTime()), new DateTime(cal.getTime())).getMinutes() % 60);

        String h_diff_s = h_diff+"";
        String m_diff_s = m_diff+"";
        if(m_diff < 10){
            m_diff_s = "0"+m_diff_s;
        }

        boolean negative = true; // negative if time of tide BEHIND current time
        long milli_diff = cal.getTime().getTime() - time.getTime().getTime();
        if(milli_diff < 0){
            negative = false;
        }

        if(negative){
            return "-"+h_diff_s+":"+m_diff_s;
        }
        else{
            return "+"+h_diff_s+":"+m_diff_s;
        }
    }
项目:levelup-java-examples    文件:CalculateDateTimeDifference.java   
@Test
public void difference_between_two_dates_joda () {

    DateTime sinceGraduation = new DateTime(1984, 6, 4, 0, 0, GregorianChronology.getInstance());
    DateTime currentDate = new DateTime(); //current date

    Days diffInDays = Days.daysBetween(sinceGraduation, currentDate);
    Hours diffInHours = Hours.hoursBetween(sinceGraduation, currentDate);
    Minutes diffInMinutes = Minutes.minutesBetween(sinceGraduation, currentDate);
    Seconds seconds = Seconds.secondsBetween(sinceGraduation, currentDate);

    logger.info(diffInDays.getDays());
    logger.info(diffInHours.getHours());
    logger.info(diffInMinutes.getMinutes());
    logger.info(seconds.getSeconds());

    assertTrue(diffInDays.getDays() >= 10697);
    assertTrue(diffInHours.getHours() >= 256747);
    assertTrue(diffInMinutes.getMinutes() >= 15404876);
    assertTrue(seconds.getSeconds() >= 924292577);

}
项目:PocketKnell    文件:KnellActivity.java   
@Override
protected void onCreate(@Nullable Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_knell);
    ButterKnife.bind(this);

    Birthday birthday = getBirthdayManager().get();
    DateTime birDateTime = new DateTime(birthday.year, birthday.month, birthday.day, 0, 0);
    Days days = Days.daysBetween(birDateTime, DateTime.now());
    Hours hours = Hours.hoursBetween(birDateTime, DateTime.now());
    Minutes minutes = Minutes.minutesBetween(birDateTime, DateTime.now());
    Weeks weeks = Weeks.weeksBetween(birDateTime, DateTime.now());
    Years years = Years.yearsBetween(birDateTime, DateTime.now());
    Months months = Months.monthsBetween(birDateTime, DateTime.now());

    Timber.d("onCreate: 年:%d", years.getYears());
    Timber.d("onCreate: 月:%d", months.getMonths());
    Timber.d("onCreate: 周:%d", weeks.getWeeks());
    Timber.d("onCreate: 天数为:%d", days.getDays());
    Timber.d("onCreate: 小时数为:%d", hours.getHours());
    Timber.d("onCreate: 分钟数为:%d", minutes.getMinutes());

    tvYear.setText(String.valueOf(years.getYears()));
    tvMonth.setText(String.valueOf(months.getMonths()));
    tvWeek.setText(String.valueOf(weeks.getWeeks()));
    tvDay.setText(String.valueOf(days.getDays()));
    tvHour.setText(String.valueOf(hours.getHours()));
    tvMinute.setText(String.valueOf(minutes.getMinutes()));
}
项目:burning-series    文件:SyncBroadcastReceiver.java   
private static long getNextSyncTime(Context context) {
    SharedPreferences prefs = getSyncPrefs(context);

    long delay = Math.min(
            prefs.getLong("delay", DEFAULT_SYNC_DELAY),
            Hours.ONE.toStandardDuration().getMillis());

    prefs.edit().putLong("delay", 2 * delay).apply();
    return SystemClock.elapsedRealtime() + delay;
}
项目:azkaban    文件:Schedule.java   
public static ReadablePeriod parsePeriodString(String periodStr) {
  ReadablePeriod period;
  char periodUnit = periodStr.charAt(periodStr.length() - 1);
  if (periodUnit == 'n') {
    return null;
  }

  int periodInt =
      Integer.parseInt(periodStr.substring(0, periodStr.length() - 1));
  switch (periodUnit) {
  case 'M':
    period = Months.months(periodInt);
    break;
  case 'w':
    period = Weeks.weeks(periodInt);
    break;
  case 'd':
    period = Days.days(periodInt);
    break;
  case 'h':
    period = Hours.hours(periodInt);
    break;
  case 'm':
    period = Minutes.minutes(periodInt);
    break;
  case 's':
    period = Seconds.seconds(periodInt);
    break;
  default:
    throw new IllegalArgumentException("Invalid schedule period unit '"
        + periodUnit);
  }

  return period;
}
项目:azkaban    文件:Utils.java   
public static ReadablePeriod parsePeriodString(String periodStr) {
  ReadablePeriod period;
  char periodUnit = periodStr.charAt(periodStr.length() - 1);
  if (periodStr.equals("null") || periodUnit == 'n') {
    return null;
  }

  int periodInt =
      Integer.parseInt(periodStr.substring(0, periodStr.length() - 1));
  switch (periodUnit) {
  case 'y':
    period = Years.years(periodInt);
    break;
  case 'M':
    period = Months.months(periodInt);
    break;
  case 'w':
    period = Weeks.weeks(periodInt);
    break;
  case 'd':
    period = Days.days(periodInt);
    break;
  case 'h':
    period = Hours.hours(periodInt);
    break;
  case 'm':
    period = Minutes.minutes(periodInt);
    break;
  case 's':
    period = Seconds.seconds(periodInt);
    break;
  default:
    throw new IllegalArgumentException("Invalid schedule period unit '"
        + periodUnit);
  }

  return period;
}
项目:azkaban    文件:Schedule.java   
public static ReadablePeriod parsePeriodString(String periodStr) {
  ReadablePeriod period;
  char periodUnit = periodStr.charAt(periodStr.length() - 1);
  if (periodUnit == 'n') {
    return null;
  }

  int periodInt =
      Integer.parseInt(periodStr.substring(0, periodStr.length() - 1));
  switch (periodUnit) {
  case 'M':
    period = Months.months(periodInt);
    break;
  case 'w':
    period = Weeks.weeks(periodInt);
    break;
  case 'd':
    period = Days.days(periodInt);
    break;
  case 'h':
    period = Hours.hours(periodInt);
    break;
  case 'm':
    period = Minutes.minutes(periodInt);
    break;
  case 's':
    period = Seconds.seconds(periodInt);
    break;
  default:
    throw new IllegalArgumentException("Invalid schedule period unit '"
        + periodUnit);
  }

  return period;
}
项目:data-polygamy    文件:FrameworkUtils.java   
public static int getTimeSteps(int tempRes, int startTime, int endTime) {

    if (startTime > endTime) {
        return 0;
    }

    int timeSteps = 0;
    DateTime start = new DateTime(((long)startTime)*1000, DateTimeZone.UTC);
    DateTime end = new DateTime(((long)endTime)*1000, DateTimeZone.UTC);

    switch(tempRes) {
    case FrameworkUtils.HOUR:
        timeSteps = Hours.hoursBetween(start, end).getHours();
        break;
    case FrameworkUtils.DAY:
        timeSteps = Days.daysBetween(start, end).getDays();
        break;
    case FrameworkUtils.WEEK:
        timeSteps = Weeks.weeksBetween(start, end).getWeeks();
        break;
    case FrameworkUtils.MONTH:
        timeSteps = Months.monthsBetween(start, end).getMonths();
        break;
    case FrameworkUtils.YEAR:
        timeSteps = Years.yearsBetween(start, end).getYears();
        break;
    default:
        timeSteps = Hours.hoursBetween(start, end).getHours();
        break;
    }
    timeSteps++;

    return timeSteps;
}
项目:data-polygamy    文件:FrameworkUtils.java   
public static int getDeltaSinceEpoch(int time, int tempRes) {
    int delta = 0;

    // Epoch
    MutableDateTime epoch = new MutableDateTime();
    epoch.setDate(0);

    DateTime dt = new DateTime(time*1000, DateTimeZone.UTC);

    switch(tempRes) {
    case FrameworkUtils.HOUR:
        Hours hours = Hours.hoursBetween(epoch, dt);
        delta = hours.getHours();
        break;
    case FrameworkUtils.DAY:
        Days days = Days.daysBetween(epoch, dt);
        delta = days.getDays();
        break;
    case FrameworkUtils.WEEK:
        Weeks weeks = Weeks.weeksBetween(epoch, dt);
        delta = weeks.getWeeks();
        break;
    case FrameworkUtils.MONTH:
        Months months = Months.monthsBetween(epoch, dt);
        delta = months.getMonths();
        break;
    case FrameworkUtils.YEAR:
        Years years = Years.yearsBetween(epoch, dt);
        delta = years.getYears();
        break;
    default:
        hours = Hours.hoursBetween(epoch, dt);
        delta = hours.getHours();
        break;
    }

    return delta;
}
项目:NaturalDateFormat    文件:RelativeDateFormat.java   
private void formatHours(DateTime now, DateTime then, StringBuilder text) {
    int hoursBetween = Hours.hoursBetween(now.toLocalTime(), then.toLocalTime()).getHours();
    if (hoursBetween == 0) {
        if (hasFormat(MINUTES)) {
            formatMinutes(now, then, text);
        } else {
            text.append(context.getString(R.string.now));
        }
    } else if (hoursBetween > 0) {    // in N hours
        text.append(context.getResources().getQuantityString(R.plurals.carbon_inHours, hoursBetween, hoursBetween));
    } else {    // N hours ago
        text.append(context.getResources().getQuantityString(R.plurals.carbon_hoursAgo, -hoursBetween, -hoursBetween));
    }
}
项目:CodePath-TodoApp    文件:TimeUtils.java   
private static String toHours(DateTime date, DateTime now) {
    int result = Hours.hoursBetween(date, now).getHours();
    if (Math.abs(result) >= 1) {
        return Math.abs(result) == 1 ? "1 hour " + (result == 1 ? "ago" : "from now") :
                toReference(Math.abs(result), result, " hours ");
    }
    return null;
}
项目:java-hod-client    文件:HodErrorITCase.java   
@Test
public void testHodReturnsApiKeyError() throws IOException {
    final TokenProxy<EntityType.Application, TokenType.Simple> tokenProxy = getConfig().getTokenRepository().insert(new AuthenticationToken<>(
        EntityType.Application.INSTANCE,
        TokenType.Simple.INSTANCE,
        DateTime.now().plus(Hours.ONE),
        "ID",
        "SECRET",
        new DateTime(1234567890L)
    ));

    testErrorCodeAndMessage(HodErrorCode.AUTHENTICATION_FAILED, "Authentication failed", () -> queryTextIndexService.queryTextIndexWithText(tokenProxy, "*", new QueryRequestBuilder()));
}