Java Code Examples for org.joda.time.Days#daysBetween()

The following examples show how to use org.joda.time.Days#daysBetween() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: ISODaysBetween.java    From spork with Apache License 2.0 6 votes vote down vote up
@Override
public Long exec(Tuple input) throws IOException
{
    if (input == null || input.size() < 2) {
        return null;
    }

    if (input.get(0) == null || input.get(1) == null) {
        return null;
    }

    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;

}
 
Example 2
Source File: CalculateDateTimeDifference.java    From levelup-java-examples with Apache License 2.0 6 votes vote down vote up
@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);

}
 
Example 3
Source File: JobInfoWriter.java    From megatron-java with Apache License 2.0 6 votes vote down vote up
private String formatLastSeenTimestamp(Long timestampInSec) {
    if ((timestampInSec == null) || (timestampInSec == 0L)) {
        return "-";
    }
    
    final String template = "@days@ (@date@)";
    String result = template;

    DateTime now = new DateTime();
    DateTime dateTime = new DateTime(1000L*timestampInSec);        
    Days d = Days.daysBetween(dateTime, now);
    int days = d.getDays();
    result = StringUtil.replace(result, "@days@", days + "");

    String date = DateUtil.formatDateTime(DateUtil.DATE_TIME_FORMAT_WITH_SECONDS, dateTime.toDate());
    result = StringUtil.replace(result, "@date@", date);
    
    return result;
}
 
Example 4
Source File: DefaultAccountStateHandler.java    From springboot-shiro-cas-mybatis with MIT License 5 votes vote down vote up
/**
 * Handle an account state warning produced by ldaptive account state machinery.
 * <p>
 * Override this method to provide custom warning message handling.
 *
 * @param warning the account state warning messages.
 * @param response Ldaptive authentication response.
 * @param configuration Password policy configuration.
 * @param messages Container for messages produced by account state warning handling.
 */
protected void handleWarning(
        final AccountState.Warning warning,
        final AuthenticationResponse response,
        final LdapPasswordPolicyConfiguration configuration,
        final List<MessageDescriptor> messages) {

    logger.debug("Handling warning {}", warning);
    if (warning == null) {
        logger.debug("Account state warning not defined");
        return;
    }

    final Calendar expDate = warning.getExpiration();
    final Days ttl = Days.daysBetween(Instant.now(), new Instant(expDate));
    logger.debug(
            "Password expires in {} days. Expiration warning threshold is {} days.",
            ttl.getDays(),
            configuration.getPasswordWarningNumberOfDays());
    if (configuration.isAlwaysDisplayPasswordExpirationWarning()
            || ttl.getDays() < configuration.getPasswordWarningNumberOfDays()) {
        messages.add(new PasswordExpiringWarningMessageDescriptor(
                "Password expires in {0} days. Please change your password at <href=\"{1}\">{1}</a>",
                ttl.getDays(),
                configuration.getPasswordPolicyUrl()));
    }
    if (warning.getLoginsRemaining() > 0) {
        messages.add(new DefaultMessageDescriptor(
                "password.expiration.loginsRemaining",
                "You have {0} logins remaining before you MUST change your password.",
                warning.getLoginsRemaining()));

    }
}
 
Example 5
Source File: DefaultAccountStateHandler.java    From cas4.0.x-server-wechat with Apache License 2.0 5 votes vote down vote up
/**
 * Handle an account state warning produced by ldaptive account state machinery.
 * <p>
 * Override this method to provide custom warning message handling.
 *
 * @param error Account state warning.
 * @param response Ldaptive authentication response.
 * @param configuration Password policy configuration.
 * @param messages Container for messages produced by account state warning handling.
 */
protected void handleWarning(
        final AccountState.Warning warning,
        final AuthenticationResponse response,
        final LdapPasswordPolicyConfiguration configuration,
        final List<Message> messages) {

    if (warning == null) {
        logger.debug("Account state warning not defined");
        return;
    }

    final Calendar expDate = warning.getExpiration();
    final Days ttl = Days.daysBetween(Instant.now(), new Instant(expDate));
    logger.debug(
            "Password expires in {} days. Expiration warning threshold is {} days.",
            ttl.getDays(),
            configuration.getPasswordWarningNumberOfDays());
    if (configuration.isAlwaysDisplayPasswordExpirationWarning()
            || ttl.getDays() < configuration.getPasswordWarningNumberOfDays()) {
        messages.add(new PasswordExpiringWarningMessage(
                "Password expires in {0} days. Please change your password at <href=\"{1}\">{1}</a>",
                ttl.getDays(),
                configuration.getPasswordPolicyUrl()));
    }
    if (warning.getLoginsRemaining() > 0) {
        messages.add(new Message(
                "password.expiration.loginsRemaining",
                "You have {0} logins remaining before you MUST change your password.",
                warning.getLoginsRemaining()));

    }
}
 
Example 6
Source File: FrameworkUtils.java    From data-polygamy with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
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;
}
 
Example 7
Source File: SQLTime.java    From spliceengine with GNU Affero General Public License v3.0 5 votes vote down vote up
@Override
  public NumberDataValue minus(DateTimeDataValue leftOperand, DateTimeDataValue rightOperand, NumberDataValue returnValue) throws StandardException {
if( returnValue == null)
	returnValue = new SQLInteger();
if(leftOperand.isNull() || rightOperand.isNull()) {
	returnValue.restoreToNull();
	return returnValue;
}
DateTime thatDate = rightOperand.getDateTime();
Days diff = Days.daysBetween(thatDate, leftOperand.getDateTime());
returnValue.setValue(diff.getDays());
return returnValue;
  }
 
Example 8
Source File: SQLDate.java    From spliceengine with GNU Affero General Public License v3.0 5 votes vote down vote up
@Override
   public NumberDataValue minus(DateTimeDataValue leftOperand, DateTimeDataValue rightOperand, NumberDataValue returnValue) throws StandardException {
	if( returnValue == null)
		returnValue = new SQLInteger();
	if(leftOperand.isNull() || rightOperand.isNull()) {
		returnValue.restoreToNull();
		return returnValue;
	}
	DateTime thatDate = rightOperand.getDateTime();
	Days diff = Days.daysBetween(thatDate, leftOperand.getDateTime());
	returnValue.setValue(diff.getDays());
	return returnValue;
}
 
Example 9
Source File: SQLTimestamp.java    From spliceengine with GNU Affero General Public License v3.0 5 votes vote down vote up
@Override
public NumberDataValue minus(DateTimeDataValue leftOperand, DateTimeDataValue rightOperand, NumberDataValue resultHolder) throws StandardException {
    if( resultHolder == null)
        resultHolder = new SQLInteger();
    if(leftOperand.isNull() || rightOperand.isNull()) {
        resultHolder.restoreToNull();
        return resultHolder;
    }
    DateTime thatDate = rightOperand.getDateTime();
    Days diff = Days.daysBetween(thatDate, leftOperand.getDateTime());
    resultHolder.setValue(diff.getDays());
    return resultHolder;
}
 
Example 10
Source File: DaysBetweenDates.java    From levelup-java-examples with Apache License 2.0 5 votes vote down vote up
@Test
public void days_between_two_dates_in_java_with_joda () {
	
	// start day is 1 day in the past
	DateTime startDate = new DateTime().minusDays(1);
	DateTime endDate = new DateTime();
	
	Days d = Days.daysBetween(startDate, endDate);
	int days = d.getDays();
	
	assertEquals(1, days);
}
 
Example 11
Source File: ClickHouseWriter.java    From beam with Apache License 2.0 4 votes vote down vote up
@SuppressWarnings("unchecked")
static void writeValue(ClickHouseRowBinaryStream stream, ColumnType columnType, Object value)
    throws IOException {

  switch (columnType.typeName()) {
    case FIXEDSTRING:
      byte[] bytes;

      if (value instanceof String) {
        bytes = ((String) value).getBytes(Charsets.UTF_8);
      } else {
        bytes = ((byte[]) value);
      }

      stream.writeBytes(bytes);
      break;

    case FLOAT32:
      stream.writeFloat32((Float) value);
      break;

    case FLOAT64:
      stream.writeFloat64((Double) value);
      break;

    case INT8:
      stream.writeInt8((Byte) value);
      break;

    case INT16:
      stream.writeInt16((Short) value);
      break;

    case INT32:
      stream.writeInt32((Integer) value);
      break;

    case INT64:
      stream.writeInt64((Long) value);
      break;

    case STRING:
      stream.writeString((String) value);
      break;

    case UINT8:
      stream.writeUInt8((Short) value);
      break;

    case UINT16:
      stream.writeUInt16((Integer) value);
      break;

    case UINT32:
      stream.writeUInt32((Long) value);
      break;

    case UINT64:
      stream.writeUInt64((Long) value);
      break;

    case ENUM8:
      Integer enum8 = columnType.enumValues().get((String) value);
      Preconditions.checkNotNull(
          enum8,
          "unknown enum value '" + value + "', possible values: " + columnType.enumValues());
      stream.writeInt8(enum8);
      break;

    case ENUM16:
      Integer enum16 = columnType.enumValues().get((String) value);
      Preconditions.checkNotNull(
          enum16,
          "unknown enum value '" + value + "', possible values: " + columnType.enumValues());
      stream.writeInt16(enum16);
      break;

    case DATE:
      Days epochDays = Days.daysBetween(EPOCH_INSTANT, (ReadableInstant) value);
      stream.writeUInt16(epochDays.getDays());
      break;

    case DATETIME:
      long epochSeconds = ((ReadableInstant) value).getMillis() / 1000L;
      stream.writeUInt32(epochSeconds);
      break;

    case ARRAY:
      List<Object> values = (List<Object>) value;
      stream.writeUnsignedLeb128(values.size());
      for (Object arrayValue : values) {
        writeValue(stream, columnType.arrayElementType(), arrayValue);
      }
      break;
  }
}
 
Example 12
Source File: NotUpdatedAlumniInfoForSpecificDaysGroup.java    From fenixedu-academic with GNU Lesser General Public License v3.0 4 votes vote down vote up
private boolean notRecentlyUpdated(DateTime now, DateTime lastModifiedDate) {
    Days days = Days.daysBetween(lastModifiedDate, now);
    return days.getDays() > daysNotUpdated;
}
 
Example 13
Source File: DateUtils.java    From dhis2-core with BSD 3-Clause "New" or "Revised" License 3 votes vote down vote up
/**
 * Calculates the number of days between the start and end-date. Note this
 * method is taking daylight saving time into account and has a performance
 * overhead.
 *
 * @param startDate the start date.
 * @param endDate   the end date.
 * @return the number of days between the start and end date.
 */
public static int daysBetween( Date startDate, Date endDate )
{
    final Days days = Days.daysBetween( new DateTime( startDate ), new DateTime( endDate ) );

    return days.getDays();
}
 
Example 14
Source File: TimeRangeUtils.java    From incubator-pinot with Apache License 2.0 3 votes vote down vote up
/**
 * Given time granularity and start time (with local time zone information), returns the bucket
 * index of the current time (with local time zone information).
 *
 * The reason to use this method to calculate the bucket index is to align the shifted data point
 * due to daylight saving time to the correct bucket index. Note that this method have no effect
 * if the input time use UTC timezone.
 *
 * For instance, considering March 13th 2016, the day DST takes effect. Assume that our daily
 * data whose timestamp is aligned at 0 am at each day, then the data point on March 14th would
 * be actually aligned to 13th's bucket. Because the two data point only has 23 hours difference.
 * Therefore, we cannot calculate the bucket index simply divide the difference between timestamps
 * by millis of 24 hours.
 *
 * We don't need to consider the case of HOURS because the size of a bucket does not change when
 * the time granularity is smaller than DAYS. In DAYS, the bucket size could be 23, 24, or 25
 * hours due to DST. In HOURS or anything smaller, the bucket size does not change. Hence, we
 * simply compute the bucket index using one fixed bucket size (i.e., interval).
 *
 * @param granularity the time granularity of the bucket
 * @param start the start time of the first bucket
 * @param current the current time
 * @return the bucket index of current time
 */
public static int computeBucketIndex(TimeGranularity granularity, DateTime start, DateTime current) {
  int index = -1;
  switch (granularity.getUnit()) {
  case DAYS:
    Days d = Days.daysBetween(start, current);
    index = d.getDays() / granularity.getSize();
    break;
  default:
    long interval = granularity.toMillis();
    index = (int) ((current.getMillis() - start.getMillis()) / interval);
  }
  return index;
}
 
Example 15
Source File: Period.java    From dhis2-core with BSD 3-Clause "New" or "Revised" License 2 votes vote down vote up
/**
 * Returns the number of days in the period, i.e. the days between the start
 * and end date.
 *
 * @return number of days in period.
 */
public int getDaysInPeriod()
{
    Days days = Days.daysBetween( new DateTime( startDate ), new DateTime( endDate ) );
    return days.getDays() + 1;
}
 
Example 16
Source File: CacheCleanerJob.java    From verigreen with Apache License 2.0 2 votes vote down vote up
private boolean isExceedThreashold(Date date) {
    
    Days daysBetweenCreationTimeAndNow = Days.daysBetween(new DateTime(date), DateTime.now());
    
    return daysBetweenCreationTimeAndNow.getDays() >= Integer.parseInt(VerigreenNeededLogic.VerigreenMap.get("daysThreashold"));
}