下面列出了怎么用org.joda.time.Days的API类实例代码及写法,或者点击链接到github查看源代码。
@Override
public long getLong(int field)
{
checkState(row != null, "No current row");
Column column = columns.get(field);
if (column.getType().getBase() == ColumnType.Base.DATE) {
return Days.daysBetween(new LocalDate(0), LocalDate.parse(row.get(column.getPosition()))).getDays();
}
if (column.getType().getBase() == ColumnType.Base.TIME) {
return LocalTime.parse(row.get(column.getPosition())).getMillisOfDay();
}
if (column.getType().getBase() == ColumnType.Base.INTEGER) {
return parseInt(row.get(column.getPosition()));
}
if (column.getType().getBase() == ColumnType.Base.DECIMAL) {
DecimalParseResult decimalParseResult = Decimals.parse(row.get(column.getPosition()));
return rescale((Long) decimalParseResult.getObject(), decimalParseResult.getType().getScale(), ((DecimalType) columnTypes.get(field)).getScale());
}
return parseLong(row.get(column.getPosition()));
}
protected static int dateDiff(Date beginDate, Date endDate, DateType type) {
//Interval interval = new Interval(beginDate.getTime(), endDate.getTime());
//Period p = interval.toPeriod();
DateTime start =new DateTime(beginDate);
DateTime end =new DateTime(endDate);
if (DateType.YEAR.equals(endDate)) {
return Years.yearsBetween(start, end).getYears();
} else if (DateType.MONTH.equals(type)) {
return Months.monthsBetween(start, end).getMonths();
} else if (DateType.WEEK.equals(type)) {
return Weeks.weeksBetween(start, end).getWeeks();
} else if (DateType.DAY.equals(type)) {
return Days.daysBetween(start, end).getDays();
} else if (DateType.HOUR.equals(type)) {
return Hours.hoursBetween(start, end).getHours();
} else if (DateType.MINUTE.equals(type)) {
return Minutes.minutesBetween(start, end).getMinutes();
} else if (DateType.SECOND.equals(type)) {
return Seconds.secondsBetween(start, end).getSeconds();
} else {
return 0;
}
}
/**
* 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();
}
}
/**
* 获得两个时间点之间的时间跨度
*
* @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");
}
}
/**
* 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++;
}
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 "";
}
}
@Override
@SuppressWarnings("EqualsBetweenInconvertibleTypes") // SpecimenType knows how to do equals(Class<?>)
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();
}
private String prepareDate(Date date){
DateTime busTimestamp = new DateTime(date);
DateTime now = new DateTime(Calendar.getInstance());
int time = Seconds.secondsBetween(busTimestamp, now).getSeconds();
if(time < 60) return context.getString(R.string.marker_seconds, String.valueOf(time));
time = Minutes.minutesBetween(busTimestamp, now).getMinutes();
if(time < 60) return context.getString(R.string.marker_minutes, String.valueOf(time));
time = Hours.hoursBetween(busTimestamp, now).getHours();
if(time < 24) return context.getString(R.string.marker_hours, String.valueOf(time));
time = Days.daysBetween(busTimestamp, now).getDays();
return context.getString(R.string.marker_days, String.valueOf(time));
}
@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;
}
@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);
}
/**
* Calculate ssl expired duration.
*
* @param expiryDateFormat the expiry date format
* @param targetExpiryDurationInt the target expiry duration int
* @return true, if successful
*/
private boolean calculateSslExpiredDuration(Date expiryDateFormat, int targetExpiryDurationInt) {
boolean isFlag = false;
if(expiryDateFormat!=null){
DateTime expiryDate = new DateTime(expiryDateFormat);
DateTime currentDate = new DateTime();
if (Days.daysBetween(currentDate, expiryDate).getDays() <= targetExpiryDurationInt) {
isFlag = true;
}
}
return isFlag;
}
@Test
public void testCanNotEditPreviousPeriodEndsSameTodayMinusDifferenceExpiryDays() {
LocalDate periodDate = new LocalDate();
String previousPeriodStart = getPreviousPeriodStart();
periodDate = periodDate.withMonthOfYear(monthStart(previousPeriodStart)).withDayOfMonth(1);
int expiryDays = Days.daysBetween(periodDate.plusMonths(2), new LocalDate()).getDays();
BimonthlyExpiryDayValidator monthlyExpiryDayValidator = new BimonthlyExpiryDayValidator(
expiryDays,
String.format(periodDate.toString(PATTERN), previousPeriodStart));
assertFalse(monthlyExpiryDayValidator.canEdit());
}
@Test
public void testCanNotEditPreviousPeriodEndsSameTodayMinusDifferenceExpiryDays() {
LocalDate periodDate = new LocalDate();
periodDate = periodDate.minusYears(1).withMonthOfYear(
DateTimeConstants.APRIL).withDayOfMonth(1);
int expiryDays = Days.daysBetween(periodDate.plusYears(1), new LocalDate()).getDays();
FinancialYearAprilExpiryDayValidator yearlyExpiryDayValidator =
new FinancialYearAprilExpiryDayValidator(
expiryDays,
periodDate.toString(PATTERN));
assertFalse(yearlyExpiryDayValidator.canEdit());
}
/**
* 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()));
}
}
/**
* 得到仿微信日期格式输出
*
* @param msgTimeMillis
* @return
*/
public static String getMsgFormatTime(long msgTimeMillis) {
DateTime nowTime = new DateTime();
// LogUtils.sf("nowTime = " + nowTime);
DateTime msgTime = new DateTime(msgTimeMillis);
// LogUtils.sf("msgTime = " + msgTime);
int days = Math.abs(Days.daysBetween(msgTime, nowTime).getDays());
// LogUtils.sf("days = " + days);
if (days < 1) {
//早上、下午、晚上 1:40
return getTime(msgTime);
} else if (days == 1) {
//昨天
return "昨天 " + getTime(msgTime);
} else if (days <= 7) {
//星期
switch (msgTime.getDayOfWeek()) {
case DateTimeConstants.SUNDAY:
return "周日 " + getTime(msgTime);
case DateTimeConstants.MONDAY:
return "周一 " + getTime(msgTime);
case DateTimeConstants.TUESDAY:
return "周二 " + getTime(msgTime);
case DateTimeConstants.WEDNESDAY:
return "周三 " + getTime(msgTime);
case DateTimeConstants.THURSDAY:
return "周四 " + getTime(msgTime);
case DateTimeConstants.FRIDAY:
return "周五 " + getTime(msgTime);
case DateTimeConstants.SATURDAY:
return "周六 " + getTime(msgTime);
}
return "";
} else {
//12月22日
return msgTime.toString("MM月dd日 " + getTime(msgTime));
}
}
/**
* Returns the number of working days between two dates (inclusive). Saturday and Sunday are not considered working days.
*/
@Function("NETWORKDAYS")
@FunctionParameters({
@FunctionParameter("startDate"),
@FunctionParameter("endDate")})
public Integer NETWORKDAYS(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 cursorLocalDate=new LocalDate(startDateObj);
LocalDate endLocalDate=new LocalDate(endDateObj);
int workingDays=0;
if(cursorLocalDate.isAfter(endLocalDate)){
// Swap data information
LocalDate tmp=cursorLocalDate;
cursorLocalDate=endLocalDate;
endLocalDate=tmp;
}
while (Days.daysBetween(cursorLocalDate, endLocalDate).getDays()>0){
int dayOfWeek = cursorLocalDate.getDayOfWeek();
if(!(dayOfWeek==DateTimeConstants.SATURDAY ||
dayOfWeek==DateTimeConstants.SUNDAY)){
workingDays++;
}
cursorLocalDate=cursorLocalDate.plusDays(1);
}
return workingDays;
}
}
@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;
}
/**
* Compare the messageStats
*/
@Override
public int compareTo(MessageStats in) {
final DateTime inDateTime = new DateTime(in.getLastAdded());
final DateTime thisDateTime = new DateTime(getLastAdded());
/* Allow some toleration */
int days = Days.daysBetween(inDateTime, thisDateTime).getDays();
if (m_numberOfDaysToConsiderCleanupPriority >= Math.abs(days)) {
/* For example, if the days diff is less than 2 days, we
* will use the occurrence count for sorting.
*/
days = 0;
}
/* Do the compare */
if (days > 0) {
/* last occurrence of this message is after in */
return 1;
} else if (days < 0) {
return -1;
} else {
if (getOccurred() > in.getOccurred()) {
return 1;
} else if (getOccurred() < in.getOccurred()) {
return -1;
} else {
return 0;
}
}
}
@Test
public void testCanNotEditPreviousPeriodEndsSameTodayMinusDifferenceMinusOneExpiryDays() {
LocalDate periodDate = new LocalDate();
periodDate = periodDate.minusYears(1).withMonthOfYear(
DateTimeConstants.APRIL).withDayOfMonth(1);
int expiryDays = Days.daysBetween(periodDate.plusYears(1), new LocalDate()).getDays() - 1;
FinancialYearAprilExpiryDayValidator yearlyExpiryDayValidator =
new FinancialYearAprilExpiryDayValidator(
expiryDays,
periodDate.toString(PATTERN));
assertFalse(yearlyExpiryDayValidator.canEdit());
}
@Test
public void testCanNotEditPreviousPeriodEndsSameTodayMinusExpiryDaysMinusOne() {
LocalDate periodDate = new LocalDate();
int previousPeriodStart = getPreviousPeriodStart();
periodDate = periodDate.withMonthOfYear(monthStart(previousPeriodStart)).withDayOfMonth(1);
int expiryDays = Days.daysBetween(periodDate.plusMonths(3), new LocalDate()).getDays() - 1;
QuarterlyExpiryDayValidator monthlyExpiryDayValidator =
new QuarterlyExpiryDayValidator(
expiryDays,
periodDate.toString(PATTERN) + previousPeriodStart);
assertFalse(monthlyExpiryDayValidator.canEdit());
}
/**
* Calculates the difference between two times, given as long values, and
* returns the period between them in the specified <code>units</code>. The
* units value must be one of:
* <pre>
* {@link #MILLISECONDS}
* {@link #SECONDS}
* {@link #MINUTES}
* {@link #HOURS}
* {@link #DAYS}
* {@link #WEEKS}
* {@link #MONTHS}
* {@link #YEARS}
* </pre>
* All values will be returned as the absolute value of the difference.
*
* @param arg1 The value to use as the minuend.
* @param arg2 The value to use as the subtrahend.
* @param units The time units to use for expressing the difference.
* @return The long value of the difference between the arguments in the
* specified units.
*/
public static long period(long arg1, long arg2, int units) {
long delta = arg1 - arg2;
DateTime start = new DateTime(arg1);
DateTime end = new DateTime(arg2);
// Compute delta into appropriate units
switch (units) {
case YEARS:
delta = Years.yearsBetween(start, end).getYears();
break;
case MONTHS:
delta = Months.monthsBetween(start, end).getMonths();
break;
case WEEKS:
delta = Weeks.weeksBetween(start, end).getWeeks();
break;
case DAYS:
delta = Days.daysBetween(start, end).getDays();
break;
case HOURS:
delta = Hours.hoursBetween(start, end).getHours();
break;
case MINUTES:
delta = Minutes.minutesBetween(start, end).getMinutes();
break;
case SECONDS:
delta = Double.valueOf(Math.floor(delta / 1000.0)).longValue();
break;
case MILLISECONDS:
// Here for completeness but already calculated
break;
default:
throw new IllegalArgumentException("Invalid units: "
+ units + " See Functions.difference(Calendar,Calendar)"
+ " for allowed values");
}
return Math.abs(delta);
}
private void formatDays(DateTime now, DateTime then, StringBuffer text) {
int daysBetween = Days.daysBetween(now.toLocalDate(), then.toLocalDate()).getDays();
if (daysBetween == 0) {
text.append(context.getString(R.string.today));
} else if (daysBetween > 0) { // in N days
text.append(context.getResources().getQuantityString(R.plurals.carbon_inDays, daysBetween, daysBetween));
} else { // N days ago
text.append(context.getResources().getQuantityString(R.plurals.carbon_daysAgo, -daysBetween, -daysBetween));
}
}
@Test
public void testCanEditPreviousPeriodEndsSameTodayMinusExpiryDaysPlusOne() {
LocalDate periodDate = new LocalDate();
periodDate = periodDate.minusWeeks(1).withDayOfWeek(DateTimeConstants.THURSDAY);
int expiryDays = Days.daysBetween(periodDate.plusDays(6), new LocalDate()).getDays() + 1;
WeeklyThursdayExpiryDayValidator weeklyExpiryDayValidator =
new WeeklyThursdayExpiryDayValidator(expiryDays,
periodDate.toString(PATTERN));
assertTrue(weeklyExpiryDayValidator.canEdit());
}
@Test
public void testCanNotEditPreviousPeriodEndsSameTodayMinusDifferenceMinusOneExpiryDays() {
LocalDate periodDate = new LocalDate();
periodDate = periodDate.minusWeeks(1).withDayOfWeek(DateTimeConstants.WEDNESDAY);
int expiryDays = Days.daysBetween(periodDate.plusDays(6), new LocalDate()).getDays() - 1;
WeeklyWednesdayExpiryDayValidator weeklyExpiryDayValidator =
new WeeklyWednesdayExpiryDayValidator(expiryDays,
periodDate.toString(PATTERN));
assertFalse(weeklyExpiryDayValidator.canEdit());
}
@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;
}
private ExternalFileResource createExternal( char uniqueeChar, byte[] constant )
{
ExternalFileResource externalFileResource = createExternalFileResource( uniqueeChar, content );
fileResourceService.saveFileResource( externalFileResource.getFileResource(), content );
externalFileResourceService.saveExternalFileResource( externalFileResource );
FileResource fileResource = externalFileResource.getFileResource();
fileResource.setCreated( DateTime.now().minus( Days.ONE ).toDate() );
fileResource.setStorageStatus( FileResourceStorageStatus.STORED );
fileResourceService.updateFileResource( fileResource );
return externalFileResource;
}
@Test
public void testCanEditPreviousPeriodEndsSameTodayMinusDifferencePlusTwoExpiryDays() {
LocalDate periodDate = new LocalDate();
periodDate = periodDate.minusYears(1).withMonthOfYear(
DateTimeConstants.JULY).withDayOfMonth(1);
int expiryDays = Days.daysBetween(periodDate.plusYears(1), new LocalDate()).getDays() + 2;
FinancialYearJulyExpiryDayValidator yearlyExpiryDayValidator =
new FinancialYearJulyExpiryDayValidator(
expiryDays,
periodDate.toString(PATTERN));
assertTrue(yearlyExpiryDayValidator.canEdit());
}
@Test
public void testCanEditPreviousPeriodEndsSameTodayMinusDifferencePlusTwoExpiryDays() {
LocalDate periodDate = new LocalDate();
periodDate = periodDate.minusYears(1).withMonthOfYear(
DateTimeConstants.APRIL).withDayOfMonth(1);
int expiryDays = Days.daysBetween(periodDate.plusYears(1), new LocalDate()).getDays() + 2;
FinancialYearAprilExpiryDayValidator yearlyExpiryDayValidator =
new FinancialYearAprilExpiryDayValidator(
expiryDays,
periodDate.toString(PATTERN));
assertTrue(yearlyExpiryDayValidator.canEdit());
}
@Test
public void testCanNotEditPreviousPeriodEndsSameTodayMinusDifferenceExpiryDays() {
LocalDate periodDate = new LocalDate();
periodDate = periodDate.minusWeeks(1).withDayOfWeek(DateTimeConstants.SUNDAY);
int expiryDays = Days.daysBetween(periodDate.plusDays(6), new LocalDate()).getDays();
WeeklySundayExpiryDayValidator weeklyExpiryDayValidator =
new WeeklySundayExpiryDayValidator(expiryDays,
periodDate.toString(PATTERN));
assertFalse(weeklyExpiryDayValidator.canEdit());
}
@Test
public void testCanNotEditPreviousPeriodEndsSameTodayMinusDifferenceExpiryDays() {
LocalDate periodDate = new LocalDate();
periodDate = periodDate.minusWeeks(1).withDayOfWeek(DateTimeConstants.SATURDAY);
int expiryDays = Days.daysBetween(periodDate.plusDays(6), new LocalDate()).getDays();
WeeklySaturdayExpiryDayValidator weeklyExpiryDayValidator =
new WeeklySaturdayExpiryDayValidator(expiryDays,
periodDate.toString(PATTERN));
assertFalse(weeklyExpiryDayValidator.canEdit());
}