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

项目:Artificial-Intelligent-chat-bot-    文件:IntervalUtils.java   
public static int getDaysBetween(final String date1, final String date2, String format){
    try {
        final DateTimeFormatter fmt =
                DateTimeFormat
                        .forPattern(format)
                        .withChronology(
                                LenientChronology.getInstance(
                                        GregorianChronology.getInstance()));
        return Days.daysBetween(
                fmt.parseDateTime(date1),
                fmt.parseDateTime(date2)
        ).getDays();
    } catch (Exception ex) {
        ex.printStackTrace();
        return 0;
    }
}
项目:human-mobility-modeling-utilities    文件:RadiusOfGyration.java   
/**
 * Calculates a list of progressing radius of gyration numbers based on time
 * unit given. Currently, day is supported.
 * 
 * @param traces
 *            location traces of an individual
 * @param unit
 *            spatial distance unit
 * @param timeUnit
 *            time unit for radius of gyration calculation. Day is supported.
 * @return an array of calculated radius of gyration.
 * @throws TimeUnitNotSupportedException 
 */
public double[] calculateRadiusOfGyrationOverTime(List<LocationTrace> traces, 
        SpatialDistanceUnit unit, TimeUnit timeUnit) throws TimeUnitNotSupportedException{
    if (timeUnit != TimeUnit.DAYS){
        throw new TimeUnitNotSupportedException(
                timeUnit + " is not supported. Please pass days as time unit.");
    }
    LocationTraceHelper traceHelper = new LocationTraceHelper();
    List<LocationTrace> selectedTraces;
    LocalDateTime firstTraceTime = traces.get(0).getLocalTime().minusMinutes(1);
    LocalDateTime lastTraceTime = traces.get(traces.size()-1).getLocalTime();
    double[] rogResults;
    LocalDateTime curentEndDate;

    int numberOfDays = Days.daysBetween(firstTraceTime, lastTraceTime).getDays();

    rogResults = new double[numberOfDays-1];

    for(int i=1; i < numberOfDays; i++ ){
        curentEndDate = firstTraceTime.plusDays(i).withHourOfDay(0).withMinuteOfHour(0).withSecondOfMinute(0);
        selectedTraces = traceHelper.selectBetweenDates(traces, firstTraceTime, curentEndDate);
        rogResults[i-1] = calculateRadiusOfGyration(selectedTraces);
    }

    return rogResults;
}
项目:CodeWatch    文件:CacheUtils.java   
/**
 * Updates the number of the days the app was used
 *
 * @param context needed to fetch defaultSharedPreferences
 */
public static void updateAppUsage(Context context) {

    long currentTime = System.currentTimeMillis();

    SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(context);
    SharedPreferences.Editor editor = sharedPreferences.edit();
    long lastUsageTime = sharedPreferences.getLong(PREF_APP_LAST_USAGE, -1);

    if (lastUsageTime == -1) {
        editor.putLong(PREF_APP_LAST_USAGE, currentTime);
        editor.putLong(PREF_START_OF_CONSECUTIVE_DAYS, currentTime);
    } else {
        //First check if it's been more than a day since last usage
        int days = Days.daysBetween(new DateTime(lastUsageTime), new DateTime(currentTime)).getDays();
        if (days > 1) {
            editor.putLong(PREF_START_OF_CONSECUTIVE_DAYS, currentTime);
        }
        editor.putLong(PREF_APP_LAST_USAGE, currentTime);
    }
    editor.apply();
}
项目:WeiXing_xmu-2016-MrCode    文件:DateUtils.java   
/**
 * 获得两个时间点之间的时间跨度
 * 
 * @param time1
 *            开始的时间点
 * @param time2
 *            结束的时间点
 * @param timeUnit
 *            跨度的时间单位 see {@link JodaTime}
 *            (支持的时间单位有DAY,HOUR,MINUTE,SECOND,MILLI)
 */
public static long lengthBetween(DateTime time1, DateTime time2,
        DurationFieldType timeUnit) {
    Duration duration = Days.daysBetween(time1, time2).toStandardDuration();
    if (timeUnit == JodaTime.DAY) {
        return duration.getStandardDays();
    } else if (timeUnit == JodaTime.HOUR) {
        return duration.getStandardHours();
    } else if (timeUnit == JodaTime.MINUTE) {
        return duration.getStandardMinutes();
    } else if (timeUnit == JodaTime.SECOND) {
        return duration.getStandardSeconds();
    } else if (timeUnit == JodaTime.MILLI) {
        return duration.getMillis();
    } else {
        throw new RuntimeException(
                "TimeUnit not supported except DAY,HOUR,MINUTE,SECOND,MILLI");
    }
}
项目:real-time-risk    文件:OptionPricer.java   
protected double fv() {

        double spot = cache.marketPrices.getUnchecked(marketPriceKey).getLastPrice();
        double sigma = cache.vols.getUnchecked(volKey).getValue();
        double riskFreeRate = cache.intRates.getUnchecked(interestRateKey).getValue();
        double strike = instrument.getStrike();

        //TODO Enhancement, allow use the asOf time from ValuationRequest for asofPricing
        LocalDate now = LocalDate.now();
        double time = ((double) Days.daysBetween(now, LocalDate.parse(Integer.toString(instrument.getExpDate()), FORMAT)).getDays()) / DAY_IN_YEAR;

        if (instrument.getOptionType() == Instrument.OptionType.P) {
            return putPrice(spot, strike, riskFreeRate, sigma, time);

        } else {
            return callPrice(spot, strike, riskFreeRate, sigma, time);
        }
    }
项目:jaf-examples    文件:JodaTimeTests.java   
@Test
public void intervalTest() {
    // 获取当前日期到本月最后一天还剩多少天
    LocalDate now = LocalDate.now();
    LocalDate lastDayOfMonth = LocalDate.now().dayOfMonth().withMaximumValue();
    System.out.println(Days.daysBetween(now, lastDayOfMonth).getDays());

    System.out.println(DateTime.now().toString(DEFAULT_DATE_FORMATTER));
    System.out.println(DateTime.now().dayOfMonth().withMaximumValue().toString(DEFAULT_DATE_FORMATTER));
    Interval interval = new Interval(DateTime.now(), DateTime.now().dayOfMonth().withMaximumValue());
    Period p = interval.toPeriod();

    System.out.println(interval.toDuration().getStandardDays());

    System.out.format("时间相差:%s 年, %s 月, %s 天, %s 时, %s 分, %s 秒", 
            p.getYears(), p.getMonths(), p.getDays(), p.getHours(), p.getMinutes(), p.getSeconds());
}
项目:UdacityAndroidBasicsNanodegree    文件:Habit.java   
public Habit(String name, int timesCompleted, String creationDate) {
    this.name = name;
    this.timesCompleted = timesCompleted;
    this.creationDate = creationDate;

    double tryingToGetTimesPerDay = 0;

    DateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss", Locale.US);
    try {
        java.util.Date creationTime = format.parse(creationDate);

        Calendar calendar = Calendar.getInstance();

        calendar.setTime(creationTime);

        int daysSinceCreation = Math.max(1, Days.daysBetween(new DateTime(creationTime), DateTime.now()).getDays());
        tryingToGetTimesPerDay = ((float) timesCompleted) / daysSinceCreation;

    } catch (ParseException e) {
        Timber.e(e, "WTF parse ");
    }

    timesPerDay = tryingToGetTimesPerDay;
}
项目:EventLock    文件:EventsBuilder.java   
void build() {
    while (cursor != null && cursor.moveToNext()) {
        int allDay = cursor.getInt(4);
        long beginTime, endTime;
        if (allDay == 1) {
            beginTime = new DateTime(cursor.getLong(2), DateTimeZone.forID(cursor.getString(6))).withZone(DateTimeZone.getDefault()).withTimeAtStartOfDay().getMillis();
            //to prevent multiple alarms at midnight. Even if current event says alarm at midnight, we anyway have loader alarm
            endTime = Long.MAX_VALUE;
        } else {
            beginTime = new DateTime(cursor.getLong(2), DateTimeZone.forID(cursor.getString(6))).withZone(DateTimeZone.getDefault()).getMillis();
            endTime = new DateTime(cursor.getLong(3), DateTimeZone.forID(cursor.getString(6))).withZone(DateTimeZone.getDefault()).getMillis();
        }
        int dayDiff = Days.daysBetween(new DateTime().withTimeAtStartOfDay().toLocalDate(), new DateTime(beginTime).toLocalDate()).getDays();
        if (dayDiff >= 0) {
            events[Enums.EventInfo.Title.ordinal()].add(getFormattedTitle(cursor.getString(0), cursor.getString(1)));
            events[Enums.EventInfo.Time.ordinal()].add(getFormattedTime(beginTime, endTime, allDay, dayDiff));
            events[Enums.EventInfo.Color.ordinal()].add(cursor.getString(5));
            times[Enums.TimesInfo.Begin.ordinal()].add(beginTime);
            times[Enums.TimesInfo.End.ordinal()].add(endTime);
        }
    }
    if (cursor != null) {
        cursor.close();
    }
}
项目: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());

}
项目:jasperreports    文件:DateTimeFunctions.java   
/**
 * Returns the number of days between two dates.
 */
@Function("DAYS")
@FunctionParameters({
    @FunctionParameter("startDate"),
    @FunctionParameter("endDate")})
public Integer DAYS(Object startDate, Object endDate){
    Date startDateObj = convertDateObject(startDate);
    if(startDateObj==null) {
        logCannotConvertToDate();
        return null;
    }
    Date endDateObj = convertDateObject(endDate);
    if(endDateObj==null){
        logCannotConvertToDate();
        return null;
    }
    else{
        LocalDate dt1=new LocalDate(startDateObj);
        LocalDate dt2=new LocalDate(endDateObj);
        return Days.daysBetween(dt1, dt2).getDays();
    }
}
项目:zum-android    文件:HomeActivity.java   
@Override
public void onLoadFinished(Loader<CheckLastVO> loader, CheckLastVO data) {
    if (data != null){

        DateTime date = new DateTime(data.getVerificationDate());
        DateTime today = new DateTime();

        int days = Days.daysBetween(date, today).getDays();

        lastVerificationTime.setVisibility(View.VISIBLE);
        lastVerificationTime.setText(getString(R.string.x_period, days));
        verification.setText(getString(R.string.last_checking));
    } else {
        verification.setText(getString(R.string.first_check));
    }
}
项目:xmu-2016-MrCode    文件:DateUtils.java   
/**
 * 获得两个时间点之间的时间跨度
 * 
 * @param time1
 *            开始的时间点
 * @param time2
 *            结束的时间点
 * @param timeUnit
 *            跨度的时间单位 see {@link JodaTime}
 *            (支持的时间单位有DAY,HOUR,MINUTE,SECOND,MILLI)
 */
public static long lengthBetween(DateTime time1, DateTime time2,
        DurationFieldType timeUnit) {
    Duration duration = Days.daysBetween(time1, time2).toStandardDuration();
    if (timeUnit == JodaTime.DAY) {
        return duration.getStandardDays();
    } else if (timeUnit == JodaTime.HOUR) {
        return duration.getStandardHours();
    } else if (timeUnit == JodaTime.MINUTE) {
        return duration.getStandardMinutes();
    } else if (timeUnit == JodaTime.SECOND) {
        return duration.getStandardSeconds();
    } else if (timeUnit == JodaTime.MILLI) {
        return duration.getMillis();
    } else {
        throw new RuntimeException(
                "TimeUnit not supported except DAY,HOUR,MINUTE,SECOND,MILLI");
    }
}
项目:BudgetMaster    文件:RepeatingPaymentUpdater.java   
private ArrayList<DateTime> getCorrectRepeatingDates(RepeatingPayment payment, DateTime now)
{
    ArrayList<DateTime> dates = new ArrayList<>();
    DateTime startDate = DateTime.parse(payment.getDate());

    //repeat every x days
    if(payment.getRepeatInterval() != 0)
    {           
        int numberOfDays = Days.daysBetween(startDate, now).getDays();          
        int occurrences = numberOfDays / payment.getRepeatInterval();
        for(int i = 0; i <= occurrences; i++)
        {
            dates.add(startDate.plusDays(i * payment.getRepeatInterval()));
        }
    }
    //repeat every month on day x
    else
    {
        int numberOfMonths = Months.monthsBetween(startDate.withDayOfMonth(payment.getRepeatMonthDay()), now).getMonths();
        for(int i = 0; i <= numberOfMonths; i++)
        {
            dates.add(startDate.plusMonths(i));
        }               
    }
    return dates;
}
项目:Daytripper    文件:IntervalUtils.java   
public static int getDaysBetween(final String date1, final String date2, String format){
    try {
        final DateTimeFormatter fmt =
                DateTimeFormat
                        .forPattern(format)
                        .withChronology(
                                LenientChronology.getInstance(
                                        GregorianChronology.getInstance()));
        return Days.daysBetween(
                fmt.parseDateTime(date1),
                fmt.parseDateTime(date2)
        ).getDays();
    } catch (Exception ex) {
        ex.printStackTrace();
        return 0;
    }
}
项目:dhis2-core    文件:PersianCalendar.java   
@Override
public DateTimeUnit fromIso( DateTimeUnit dateTimeUnit )
{
    if ( dateTimeUnit.getYear() >= START_PERSIAN.getYear() &&
        dateTimeUnit.getYear() <= STOP_PERSIAN.getYear() )
    {
        return new DateTimeUnit( dateTimeUnit.getYear(), dateTimeUnit.getMonth(), dateTimeUnit.getDay(),
            dateTimeUnit.getDayOfWeek(), false );
    }

    if ( dateTimeUnit.getYear() < START_ISO.getYear() || dateTimeUnit.getYear() > STOP_ISO.getYear() )
    {
        throw new InvalidCalendarParametersException(
            "Illegal ISO year, must be between " + START_ISO.getYear() + " and " + STOP_ISO.getYear() +
                ", was given " + dateTimeUnit.getYear() );
    }

    DateTime start = START_ISO.toJodaDateTime();
    DateTime end = dateTimeUnit.toJodaDateTime();

    return plusDays( START_PERSIAN, Days.daysBetween( start, end ).getDays() );
}
项目:RememBirthday    文件:Reminder.java   
/**
 * Create default auto message for date of anniversary
 */
public Reminder(Date dateEvent, int minuteBeforeEvent) {
    this.id = ID_UNDEFINED;
    this.dateEvent = dateEvent;
    this.dateEvent = new DateTime(this.dateEvent)
            .withHourOfDay(0)
            .withMinuteOfHour(0)
            .withSecondOfMinute(0)
            .withMillisOfSecond(0)
            .toDate();
    DateTime dateReminder = new DateTime(dateEvent).minusMinutes(minuteBeforeEvent);
    this.hourOfDay = dateReminder.getHourOfDay();
    this.minuteOfHour = dateReminder.getMinuteOfHour();
    this.daysBefore = Days.daysBetween(dateReminder, new DateTime(dateEvent)).getDays();
    if(minuteBeforeEvent > 0)
        this.daysBefore++;
}
项目:pitanga-system    文件:FrmRecebimento.java   
private void verificaAtraso(DateTime vencimento, DateTime recebimento) {

        System.out.print(vencimento);

        int dias = Days.daysBetween(vencimento, recebimento).getDays();
        if (dias > 0) {
            if (dias == 1) {
                lblAtraso.setText(dias + " dia de atraso.");
            } else {
                lblAtraso.setText(dias + " dias de atraso.");
            }
        } else if (dias < 0) {
            if (Math.abs(dias) == 1) {
                lblAtraso.setText(Math.abs(dias) + " dia de antecipação.");
            } else {
                lblAtraso.setText(Math.abs(dias) + " dias de antecipação.");
            }
        } else {
            lblAtraso.setText("");
        }
    }
项目:program-ab    文件:IntervalUtils.java   
public static int getDaysBetween(final String date1, final String date2, String format){
    try {
        final DateTimeFormatter fmt =
                DateTimeFormat
                        .forPattern(format)
                        .withChronology(
                                LenientChronology.getInstance(
                                        GregorianChronology.getInstance()));
        return Days.daysBetween(
                fmt.parseDateTime(date1),
                fmt.parseDateTime(date2)
        ).getDays();
    } catch (Exception ex) {
        ex.printStackTrace();
        return 0;
    }
}
项目:zee-jenkins    文件:ZephyrSoapClient.java   
public static int fetchProjectDuration(ZephyrConfigModel zephyrData)
        throws DatatypeConfigurationException {

    String token = initializeClient(zephyrData);
    int daysBtwnProjectStartEndDate = -1;
    RemoteProject projectById = null;
    try {
        projectById = client.getProjectById(
                zephyrData.getZephyrProjectId(), token);
    } catch (ZephyrServiceException e) {
        ZeeReporter.logger.print("Problem Getting Project ID");
        return daysBtwnProjectStartEndDate;
    }

    XMLGregorianCalendar projectStartDate = projectById.getStartDate();
    XMLGregorianCalendar projectEndDate = projectById.getEndDate();

    if (projectEndDate != null) {
        daysBtwnProjectStartEndDate = Days.daysBetween(
                new LocalDate(projectStartDate.toGregorianCalendar()),
                new LocalDate(projectEndDate.toGregorianCalendar()))
                .getDays();
    }

    return daysBtwnProjectStartEndDate;
}
项目:Agamemnon    文件:SpeedAlertDao.java   
private ArrayList getDateList(String startDateTime, String endDateTime)
{
    ArrayList dateList = new ArrayList();
    LocalDate sDate = new LocalDate();
    LocalDate eDate = new LocalDate();
    try {   
        sDate = LocalDate.parse(startDateTime.substring(0,10));
        eDate = LocalDate.parse(endDateTime.substring(0,10));
    }
    catch (Exception e) {
        e.printStackTrace();
    }

    int days = Days.daysBetween(sDate, eDate).getDays();
    for (int i=days; i>=0; i--)
    {
        LocalDate d = sDate.plusDays(i);
        dateList.add(d.toString("yyyy-MM-dd"));
    }   

    //System.out.println(dateList);
    return dateList;
}
项目: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;
}
项目:evend    文件:UserData.java   
public void setEventDaysAttending(DateTime eventStartDate,
        DateTime eventEndDate) {
    int daysCount = Days.daysBetween(eventStartDate.toLocalDate(),
            eventEndDate.toLocalDate()).getDays() + 1;

    this.eventDaysAttending = new Boolean[daysCount];
    java.util.Arrays.fill(this.eventDaysAttending, false);

    for (int i = 0; i < daysCount; i++) {
        if (eventStartDate.plusDays(i).isAfter(attendanceEndDate)) {
            break;
        }

        if (attendanceStartDate.isEqual(eventStartDate.plusDays(i))
                || eventStartDate.plusDays(i).isAfter(attendanceStartDate)) {
            eventDaysAttending[i] = true;
        }
    }
}
项目:evend    文件:EventCalendarAdapterTest.java   
protected void setUp() throws Exception {
    actualContext = getContext();
    int daysCount = Days.daysBetween(new DateTime(startDate).toLocalDate(),
            new DateTime(endDate).toLocalDate()).getDays() + 1;
    eventDays = new Boolean[daysCount];

    // We make even days true and odd days false
    for (int i = 0; i < eventDays.length; i++) {
        if (i % 2 == 0) {
            eventDays[i] = true;
        } else {
            eventDays[i] = false;
        }
    }

    eca = new EventCalendarAdapter(actualContext, startDate, endDate,
            eventDays);

}
项目:GOG    文件:DataHelper.java   
public static int getDiferencaEntreDatasEmDias(Date date1, Date date2) {
    int dias = 0;

    DateTimeZone BRAZIL = DateTimeZone.forID("America/Sao_Paulo");
    DateTime start = new LocalDate(date1.getTime(), BRAZIL).toDateTimeAtStartOfDay();
    DateTime end = new LocalDate(date2.getTime(), BRAZIL).toDateTimeAtStartOfDay();
    Days days = Days.daysBetween(start, end);

    if(days.isGreaterThan(null)) {
        dias = days.getDays();
    } else {
        days = days.negated();
        if(days.isGreaterThan(null)) {
            dias = days.getDays();
        }
    }

    return dias;
}
项目:GOG    文件:ManifestacaoUtils.java   
public static int getDiasAtrasoEncaminahmento(TbEncaminhamento encaminhamento) {
    int diasEmAtraso = 0;

    if(StatusEncaminhamentoEnum.ENCAMINHADA.getId().equals(encaminhamento.getStEncaminhamento())) {
        Date dataLimiteParaResponder = getDataLimiteAtendimentoUnidade(encaminhamento);
        DateTimeZone BRAZIL = DateTimeZone.forID("America/Sao_Paulo");
        DateTime start = new LocalDate(dataLimiteParaResponder.getTime(), BRAZIL).toDateTimeAtStartOfDay();
        DateTime end = new LocalDate(new Date().getTime(), BRAZIL).toDateTimeAtStartOfDay();
        Days days = Days.daysBetween(start, end);

        if(days.isGreaterThan(null)) {
            diasEmAtraso = days.getDays();
        }
    }

    return diasEmAtraso;
}
项目:motech    文件:MotechAuthenticationProvider.java   
/**
 * If user with given username exists and is active then authenticates and returns him. Updates the status of the
 * user when password has been expired.
 *
 * @param username username of user
 * @param authentication data used for authentication
 * @return the user information
 */
@Override
@Transactional
protected UserDetails retrieveUser(String username, UsernamePasswordAuthenticationToken authentication) {
    MotechUser user = motechUsersDao.findByUserName(username);
    if (user == null) {
        throw new BadCredentialsException(USER_NOT_FOUND);
    } else if (!user.isActive()) {
        throw new LockedException(USER_BLOCKED);
    } else {
        if (settingService.getNumberOfDaysToChangePassword() > 0 &&
                Days.daysBetween(user.getSafeLastPasswordChange(), DateUtil.now()).getDays() >= settingService.getNumberOfDaysToChangePassword()) {
            user.setUserStatus(UserStatus.MUST_CHANGE_PASSWORD);
            motechUsersDao.update(user);
        }
        authentication.setDetails(new MotechUserProfile(user));
        return new User(user.getUserName(), user.getPassword(), user.isActive(), true, !UserStatus.MUST_CHANGE_PASSWORD.equals(user.getUserStatus()),
                !UserStatus.BLOCKED.equals(user.getUserStatus()), authoritiesService.authoritiesFor(user));
    }
}
项目: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 "";
    }
}
项目:akuz-java    文件:TWeekdays.java   
/**
 * Calculate the distance in weekdays from one date 
 * to another, where both dates must be weekdays.
 * 
 */
public static int distance(final TDate date1, final TDate date2) {
    checkWeekday(date1);
    checkWeekday(date2);
    final int days = Days.daysBetween(
            date1.get(), 
            date2.get())
            .getDays();
    final int fullWeeks = days / 7;
    final int daysRemaining = days % 7;
    final int weekdaysAfterWeeks = fullWeeks * 5;
    if (daysRemaining == 0) {
        return weekdaysAfterWeeks;
    }
    final int step = daysRemaining < 0 ? -1 : 1;
    TDate date = add(date1, weekdaysAfterWeeks);
    int weekdaysRemaining = 0;
    while (!date.equals(date2)) {
        weekdaysRemaining += step;
        date = add(date, step);
    }
    return weekdaysAfterWeeks + weekdaysRemaining;
}
项目: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();
}
项目:tink    文件:PaymentMethodTokenRecipientTest.java   
@Test
public void testShouldSucceedIfMessageIsNotExpired() throws Exception {
  PaymentMethodTokenSender sender =
      new PaymentMethodTokenSender.Builder()
          .senderSigningKey(GOOGLE_SIGNING_PRIVATE_KEY_PKCS8_BASE64)
          .recipientId(RECIPIENT_ID)
          .rawUncompressedRecipientPublicKey(MERCHANT_PUBLIC_KEY_BASE64)
          .build();
  PaymentMethodTokenRecipient recipient =
      new PaymentMethodTokenRecipient.Builder()
          .senderVerifyingKeys(GOOGLE_VERIFYING_PUBLIC_KEYS_JSON)
          .recipientId(RECIPIENT_ID)
          .addRecipientPrivateKey(MERCHANT_PRIVATE_KEY_PKCS8_BASE64)
          .build();

  String ciphertext =
      sender.seal(
          new JSONObject()
              .put(
                  "messageExpiration",
                  // One day in the future
                  String.valueOf(Instant.now().plus(Days.ONE.toStandardDuration()).getMillis()))
              .put("someKey", "someValue")
              .toString());
  assertEquals("someValue", new JSONObject(recipient.unseal(ciphertext)).getString("someKey"));
}
项目:jpmml-evaluator    文件:TypeUtil.java   
/**
 * @see DataType#DATE_DAYS_SINCE_1960
 * @see DataType#DATE_DAYS_SINCE_1970
 * @see DataType#DATE_DAYS_SINCE_1980
 */
static
private DaysSinceDate toDaysSinceDate(Object value, LocalDate epoch){

    if(value instanceof DaysSinceDate){
        DaysSinceDate period = (DaysSinceDate)value;

        if((period.getEpoch()).equals(epoch)){
            return period;
        }

        Days difference = Days.daysBetween(epoch, period.getEpoch()).plus(period.getDays());

        return new DaysSinceDate(epoch, difference);
    }

    throw new TypeCheckException(getDaysDataType(epoch), value);
}
项目:kansalaisaloite    文件:InitiativeInfoTest.java   
@Test
public void isVotingSuspended_is_true_if_votingInProgress_and_notEnoughSupport_and_minSupportDurationEnded() {

    int minSupportCountForSearch = 50;
    Days minSupportCountDuration = Days.days(1);

    initiativeInfo.setStartDate(TWO_DAYS_AGO);
    initiativeInfo.assignEndDate(TODAY);
    initiativeInfo.assignSupportCount(minSupportCountForSearch-1);

    // Assert that the state is what we wanted.
    assert(initiativeInfo.isVotingInProggress(TODAY));
    assert(!initiativeInfo.hasTotalSupportCountAtLeast(minSupportCountForSearch));
    assert(initiativeInfo.isMinSupportCountDurationEnded(minSupportCountDuration, TODAY));

    assertThat(initiativeInfo.isVotingSuspended(minSupportCountForSearch, minSupportCountDuration, TODAY), is(true));
}
项目:kansalaisaloite    文件:InitiativeInfoTest.java   
@Test
public void isVotingSuspended_is_false_if_has_required_minSupportCount() {

    int minSupportCountForSearch = 50;
    Days minSupportCountDuration = Days.days(1);

    initiativeInfo.setStartDate(TWO_DAYS_AGO);
    initiativeInfo.assignEndDate(TOMORROW);
    initiativeInfo.assignSupportCount(minSupportCountForSearch+1);

    // Assert that the state is what we wanted.
    assert(initiativeInfo.isVotingInProggress(TODAY));
    assert(initiativeInfo.hasTotalSupportCountAtLeast(minSupportCountForSearch));
    assert(initiativeInfo.isMinSupportCountDurationEnded(minSupportCountDuration, TODAY));

    assertThat(initiativeInfo.isVotingSuspended(minSupportCountForSearch, minSupportCountDuration, TODAY), is(false));
}
项目:kansalaisaloite    文件:InitiativeDaoSearchTest.java   
@Test
public void find_with_show_only_running_does_not_show_if_not_enough_supports_and_minSupportCountDuration_has_ended() {
    testHelper.create(new TestHelper.InitiativeDraft(userId)
            .withState(InitiativeState.ACCEPTED)
            .withSupportCount(49)
            .isRunning(day_before_yesterday, far_in_the_future));

    Long hasEnoughtSupports = testHelper.create(new TestHelper.InitiativeDraft(userId)
            .withState(InitiativeState.ACCEPTED)
            .withSupportCount(50)
            .isRunning(day_before_yesterday, far_in_the_future));

    InitiativeSearch search = initiativeSearch();
    search.setShow(Show.running);

    InitiativeSettings.MinSupportCountSettings supportCountSettings
            = new InitiativeSettings.MinSupportCountSettings(50, Days.days(1)); // Ended yesterday
    List<InitiativeInfo> result = initiativeDao.findInitiatives(search, userId, supportCountSettings).list;

    assertThat(result.size(), is(1));
    assertThat(result.get(0).getId(), is(hasEnoughtSupports));
}
项目:kansalaisaloite    文件:InitiativeDaoSearchTest.java   
@Test
public void find_with_show_only_ended_shows_if_not_enough_supports_and_minSupportDuration_time_has_ended() {
    Long notEnoughSupportsAndMinSupportTimeEnded = testHelper.create(new TestHelper.InitiativeDraft(userId)
            .withState(InitiativeState.ACCEPTED)
            .withSupportCount(49)
            .isRunning(day_before_yesterday, far_in_the_future));

    testHelper.create(new TestHelper.InitiativeDraft(userId)
            .withState(InitiativeState.ACCEPTED)
            .withSupportCount(50)
            .isRunning(day_before_yesterday, far_in_the_future));

    InitiativeSearch search = initiativeSearch();
    search.setShow(Show.ended);

    InitiativeSettings.MinSupportCountSettings supportCountSettings
            = new InitiativeSettings.MinSupportCountSettings(50, Days.days(1)); // Ended yesterday
    List<InitiativeInfo> result = initiativeDao.findInitiatives(search, userId, supportCountSettings).list;

    assertThat(result.size(), is(1));
    assertThat(result.get(0).getId(), is(notEnoughSupportsAndMinSupportTimeEnded));
}
项目:kansalaisaloite    文件:InitiativeDaoSearchTest.java   
@Test
public void find_with_show_only_ended_does_not_show_if_not_enough_supports_but_minSupportDuration_time_has_not_ended() {
    testHelper.create(new TestHelper.InitiativeDraft(userId)
            .withState(InitiativeState.ACCEPTED)
            .withSupportCount(49)
            .isRunning(day_before_yesterday, far_in_the_future));

    testHelper.create(new TestHelper.InitiativeDraft(userId)
            .withState(InitiativeState.ACCEPTED)
            .withSupportCount(50)
            .isRunning(day_before_yesterday, far_in_the_future));

    InitiativeSearch search = initiativeSearch();
    search.setShow(Show.ended);

    InitiativeSettings.MinSupportCountSettings supportCountSettings
            = new InitiativeSettings.MinSupportCountSettings(50, Days.days(2)); // Ending today, inclusive
    List<InitiativeInfo> result = initiativeDao.findInitiatives(search, userId, supportCountSettings).list;

    assertThat(result.size(), is(0));
}
项目:Crosslinks    文件:ProcessorController.java   
private StartableStatus getStartStatus() {
    if (Mode.DISABLED.equals(getMode())) {
        return new StartableStatus(false, "in mode " + getMode().toString());
    }
    else if (isActive()) {
        return new StartableStatus(false, "currently active");
    }
    else if (!isOk()) {
        int minutesBetween = Minutes.minutesBetween(new DateTime(ended), new DateTime()).getMinutes();
        return new StartableStatus(minutesBetween > pauseOnAbort, "waited " + minutesBetween + " of " + pauseOnAbort + " minutes since " + getStatus());
    }
    else if (isForced()) {
        return new StartableStatus(true, "isForced");
    }
    else if (getDateLastCrawled() == null) {
        return new StartableStatus(true, "never finished crawl before");
    }
    else {
        int daysBetween = Days.daysBetween(new DateTime(getDateLastCrawled()), new DateTime()).getDays();
        return  new StartableStatus(daysBetween > staleDays, "waited " + daysBetween + " of " + staleDays + " days");
    }
}
项目:manydesigns.cn    文件:AbstractMonth.java   
public AbstractMonth(DateMidnight referenceDateMidnight) {
    logger.debug("Initializing month");
    this.referenceDateMidnight = referenceDateMidnight;
    logger.debug("Reference date midnight: {}", referenceDateMidnight);

    monthStart = referenceDateMidnight.withDayOfMonth(1);
    monthEnd = monthStart.plusMonths(1);
    monthInterval = new Interval(monthStart, monthEnd);
    logger.debug("Month interval: {}", monthInterval);

    daysCount = Days.daysIn(monthInterval).getDays();
    logger.debug("Initializing {} days", daysCount);

    days = createDaysArray(daysCount);
    DateMidnight dayStart = monthStart;
    for (int i = 0; i < daysCount; i++) {
        DateMidnight dayEnd = dayStart.plusDays(1);
        days[i] = createDay(dayStart, dayEnd);

        // advance to next day
        dayStart = dayEnd;
    }
}
项目:spork-streaming    文件:ISODaysBetween.java   
@Override
public Long exec(Tuple input) throws IOException
{
    if (input == null || input.size() < 2) {
        return null;
    }

    // Set the time to default or the output is in UTC
    DateTimeZone.setDefault(DateTimeZone.UTC);

    DateTime startDate = new DateTime(input.get(0).toString());
    DateTime endDate = new DateTime(input.get(1).toString());

    // Larger date first
    Days d = Days.daysBetween(endDate, startDate);
    long days = d.getDays();

    return days;

}
项目: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;
}