下面列出了怎么用org.joda.time.Months的API类实例代码及写法,或者点击链接到github查看源代码。
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;
}
}
public Calendar(DateTime firstMonth, DateTime lastMonth) {
this.firstMonth = firstMonth;
this.firstDayOfWeek = java.util.Calendar.getInstance(Locale.getDefault()).getFirstDayOfWeek();
DateTime startMonth = firstMonth.plusMonths(1);
int monthsBetweenCount = Months.monthsBetween(firstMonth, lastMonth).getMonths();
months = new ArrayList<>();
months.add(firstMonth);
currentMonth = firstMonth;
DateTime monthToAdd = new DateTime(startMonth.getYear(), startMonth.getMonthOfYear(), 1, 0, 0);
for (int i = 0; i <= monthsBetweenCount; i++) {
months.add(monthToAdd);
monthToAdd = monthToAdd.plusMonths(1);
}
}
/**
* Returns the number of months between two dates.
*/
@Function("MONTHS")
@FunctionParameters({
@FunctionParameter("startDate"),
@FunctionParameter("endDate")})
public Integer MONTHS(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 Months.monthsBetween(dt1, dt2).getMonths();
}
}
@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();
}
@Override
public Long exec(Tuple input) throws IOException
{
if (input == null || input.size() < 2 || input.get(0) == null || input.get(1) == null) {
return null;
}
DateTime startDate = (DateTime) input.get(0);
DateTime endDate = (DateTime) input.get(1);
// Larger value first
Months m = Months.monthsBetween(endDate, startDate);
// joda limitation, only integer range, at the risk of overflow, need to be improved
return (long) m.getMonths();
}
@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 value first
Months m = Months.monthsBetween(endDate, startDate);
long months = m.getMonths();
return months;
}
public boolean areContactsRecent(final Class<? extends PartyContact> contactClass, final int daysNotUpdated) {
final List<? extends PartyContact> partyContacts = getPartyContacts(contactClass);
boolean isUpdated = false;
for (final PartyContact partyContact : partyContacts) {
if (partyContact.getLastModifiedDate() == null) {
isUpdated = isUpdated || false;
} else {
final DateTime lastModifiedDate = partyContact.getLastModifiedDate();
final DateTime now = new DateTime();
final Months months = Months.monthsBetween(lastModifiedDate, now);
if (months.getMonths() > daysNotUpdated) {
isUpdated = isUpdated || false;
} else {
isUpdated = isUpdated || true;
}
}
}
return isUpdated;
}
public static int getMonthsBetween(final String date1, final String date2, String format){
try {
final DateTimeFormatter fmt =
DateTimeFormat
.forPattern(format)
.withChronology(
LenientChronology.getInstance(
GregorianChronology.getInstance()));
return Months.monthsBetween(
fmt.parseDateTime(date1),
fmt.parseDateTime(date2)
).getMonths();
} catch (Exception ex) {
ex.printStackTrace();
return 0;
}
}
private String getFrequencyElseNull() {
final SortedSet<InvoiceItem> items = invoice.getItems();
if(items.isEmpty()) {
return null;
}
final InvoiceItem item = items.first();
final LocalDate startDate = item.getStartDate();
final LocalDate endDate = item.getEndDate();
if(startDate == null || endDate == null) {
return null;
}
Months months = Months.monthsBetween(startDate, endDate.plusDays(1));
switch (months.getMonths()) {
case 12:
return "YEAR";
case 3:
return "QUARTER";
case 1:
return "MONTH";
}
return null;
}
public void setCurrentmonth(LocalDate currentmonth){
if (currentmonth==null)return;
LocalDate mindateobj=mindate.toDateTimeAtStartOfDay().dayOfMonth().withMinimumValue().toLocalDate();
LocalDate current=currentmonth.dayOfMonth().withMaximumValue();
int months= Months.monthsBetween(mindateobj,current).getMonths();
if (viewPager.getCurrentItem()!=months){
viewPager.setCurrentItem(months,false);
viewPager.getAdapter().notifyDataSetChanged();
}
}
public CreditCard(CreditCardNumber number, String cardHolderName, Months expiryMonth, Years expiryYear) {
super();
this.number = number;
this.cardHolderName = cardHolderName;
this.expiryMonth = expiryMonth;
this.expiryYear = expiryYear;
}
@Override
public IntervalWindow assignWindow(Instant timestamp) {
DateTime datetime = new DateTime(timestamp, timeZone);
int monthOffset =
Months.monthsBetween(startDate.withDayOfMonth(dayOfMonth), datetime).getMonths()
/ number
* number;
DateTime begin = startDate.withDayOfMonth(dayOfMonth).plusMonths(monthOffset);
DateTime end = begin.plusMonths(number);
return new IntervalWindow(begin.toInstant(), end.toInstant());
}
private void formatMonths(DateTime now, DateTime then, StringBuffer text) {
int monthsBetween = Months.monthsBetween(now.toLocalDate(), then.toLocalDate()).getMonths();
if (monthsBetween == 0) {
if ((format & DAYS) != 0) {
formatDays(now, then, text);
} else {
text.append(context.getString(R.string.thisMonth));
}
} else if (monthsBetween > 0) { // in N months
text.append(context.getResources().getQuantityString(R.plurals.carbon_inMonths, monthsBetween, monthsBetween));
} else { // N months ago
text.append(context.getResources().getQuantityString(R.plurals.carbon_monthsAgo, -monthsBetween, -monthsBetween));
}
}
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;
}
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;
}
public static Integer monthsBetween(String start, String end) throws ParseException {
if (isEmpty(start) || isEmpty(end)) {
return 0;
}
DateTime startDate = new DateTime(start);
DateTime endDate = new DateTime(end);
return Months.monthsBetween(startDate.withDayOfMonth(1), endDate.withDayOfMonth(1)).getMonths();
}
@TLFunctionAnnotation("Returns the difference between dates")
public static final Long dateDiff(TLFunctionCallContext context, Date lhs, Date rhs, DateFieldEnum unit) {
if (unit == DateFieldEnum.MILLISEC) { // CL-1087
return lhs.getTime() - rhs.getTime();
}
long diff = 0;
switch (unit) {
case SECOND:
// we have the difference in seconds
diff = (long) Seconds.secondsBetween(new DateTime(rhs.getTime()), new DateTime(lhs.getTime())).getSeconds();
break;
case MINUTE:
// how many minutes'
diff = (long) Minutes.minutesBetween(new DateTime(rhs.getTime()), new DateTime(lhs.getTime())).getMinutes();
break;
case HOUR:
diff = (long) Hours.hoursBetween(new DateTime(rhs.getTime()), new DateTime(lhs.getTime())).getHours();
break;
case DAY:
// how many days is the difference
diff = (long) Days.daysBetween(new DateTime(rhs.getTime()), new DateTime(lhs.getTime())).getDays();
break;
case WEEK:
// how many weeks
diff = (long) Weeks.weeksBetween(new DateTime(rhs.getTime()), new DateTime(lhs.getTime())).getWeeks();
break;
case MONTH:
diff = (long) Months.monthsBetween(new DateTime(rhs.getTime()), new DateTime(lhs.getTime())).getMonths();
break;
case YEAR:
diff = (long) Years.yearsBetween(new DateTime(rhs.getTime()), new DateTime(lhs.getTime())).getYears();
break;
default:
throw new TransformLangExecutorRuntimeException("Unknown time unit " + unit);
}
return diff;
}
/**
* 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);
}
/**
* 11
* Implements the MONTH_BETWEEN function
* if any of the input values are null, the function will return -1. Else, it will return an positive double.
*/
public static double MONTH_BETWEEN(Date source1, Date source2) {
if (source1 == null || source2 == null) return -1;
DateTime dt1 = new DateTime(source1);
DateTime dt2 = new DateTime(source2);
return Months.monthsBetween(dt1, dt2).getMonths();
}
/**
* 获得两个日期距离几个月
*
* @return
*/
public static int getIntervalMonths(LocalDate date1, LocalDate date2) {
date1 = date1.withDayOfMonth(1);
date2 = date2.withDayOfMonth(1);
return Months.monthsBetween(date1, date2).getMonths();
}
/**
* Protected setter to allow binding the expiration date.
*
* @param date
*/
protected void setExpirationDate(LocalDate date) {
this.expiryYear = Years.years(date.getYear());
this.expiryMonth = Months.months(date.getMonthOfYear());
}
public static int getMonthsBetween(String startDate, String endDate) {
DateTime s = new DateTime( getStrYMD(startDate.replaceAll("/", "-"), "-") );
DateTime e = new DateTime( getStrYMD(endDate.replaceAll("/", "-"), "-") );
return Months.monthsBetween(s, e).getMonths();
}
@Transactional(readOnly = false)
@SuppressWarnings("unchecked")
public void sendEmailReminders() {
try {
int currentDayOfWeek = new DateTime().getDayOfWeek();
int currentDayOfMonth = new DateTime().getDayOfMonth();
DateTime todayDateTime = new DateTime();
for (SurveyDefinition surveyDefinition : surveyDefinitionDAO.findAllInternal()){
if (surveyDefinition.getSendAutoReminders()&& surveyDefinition.getUsers().size()>0 && surveyDefinition.getStatusAsString().equals("P")) {
Date lastSentDate = surveyDefinition.getAutoReminderLastSentDate();
switch (surveyDefinition.getAutoRemindersFrequency()) {
case WEEKLY:
int weeks;
if (lastSentDate !=null) {weeks = Weeks.weeksBetween(new DateTime(lastSentDate),todayDateTime).getWeeks();
}
else {weeks = 1000;}
if (weeks >= surveyDefinition.getAutoRemindersWeeklyOccurrence()) {
for (Day day : surveyDefinition.getAutoRemindersDays()) {
if (day.getId().equals(new Long(currentDayOfWeek))) {
sendEmailReminder(surveyDefinition);
}
}
}
break;
case MONTHLY:
int months;
if (lastSentDate !=null) {months = Months.monthsBetween(new DateTime(lastSentDate), todayDateTime).getMonths();
}
else {months = 1000;}
if (months>=surveyDefinition.getAutoRemindersMonthlyOccurrence() && surveyDefinition.getAutoRemindersDayOfMonth().equals(currentDayOfMonth)) {
sendEmailReminder(surveyDefinition);
}
break;
}
}
}
}
catch (RuntimeException e) {
log.error(e.getMessage(),e);
}
}
@Test
public void creates_instance_of_Months() {
Months months = fixture.create(Months.class);
assertThat(months, notNullValue());
assertThat(months, is(Months.months(12)));
}
/**
* Calculates the number of months 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 months between the start and end date.
*/
public static int monthsBetween( Date startDate, Date endDate )
{
final Months days = Months.monthsBetween( new DateTime( startDate ), new DateTime( endDate ) );
return days.getMonths();
}
@Test
public void months_between_two_dates_in_java_with_joda () {
DateTime start = new DateTime(2005, 1, 1, 0, 0, 0, 0);
DateTime end = new DateTime(2006, 1, 1, 0, 0, 0, 0);
Months months = Months.monthsBetween(start, end);
int monthsInYear = months.getMonths();
assertEquals(12, monthsInYear);
}