Java Code Examples for org.joda.time.DateTime#plusMonths()

The following examples show how to use org.joda.time.DateTime#plusMonths() . 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: GanttDiagram.java    From fenixedu-academic with GNU Lesser General Public License v3.0 6 votes vote down vote up
private void generateYearsViewAndMonths() {

        DateTime firstMonthDateTime = getFirstInstant();
        DateTime lastMontDateTime = getLastInstant();

        if (firstMonthDateTime != null && lastMontDateTime != null) {
            while ((firstMonthDateTime.getYear() < lastMontDateTime.getYear())
                    || (firstMonthDateTime.getYear() == lastMontDateTime.getYear() && firstMonthDateTime.getMonthOfYear() <= lastMontDateTime
                            .getMonthOfYear())) {

                getMonths().add(firstMonthDateTime);

                if (getYearsView().containsKey(Integer.valueOf(firstMonthDateTime.getYear()))) {
                    getYearsView().put(Integer.valueOf(firstMonthDateTime.getYear()),
                            getYearsView().get(Integer.valueOf(firstMonthDateTime.getYear())) + 1);
                } else {
                    getYearsView().put(Integer.valueOf(firstMonthDateTime.getYear()), 1);
                }

                firstMonthDateTime = firstMonthDateTime.plusMonths(1);
            }
        }
    }
 
Example 2
Source File: DatetimeUtil.java    From stategen with GNU Affero General Public License v3.0 6 votes vote down vote up
/**
 * Gets the interval date time.
 *
 * @param curr the curr
 * @param type the type
 * @param interval the interval
 * @return the interval date time
 */
protected static DateTime plusDateTime(DateTime curr, DateType type, int interval) {
    DateTime result = curr;
    if (DateType.YEAR.equals(type)) {
        result = curr.plusYears(interval);
    } else if (DateType.MONTH.equals(type)) {
        result = curr.plusMonths(interval);
    } else if (DateType.WEEK.equals(type)) {
        result = curr.plusWeeks(interval);
    } else if (DateType.DAY.equals(type)) {
        result = curr.plusDays(interval);
    } else if (DateType.HOUR.equals(type)) {
        result = curr.plusHours(interval);
    } else if (DateType.MINUTE.equals(type)) {
        result = curr.plusMinutes(interval);
    } else if (DateType.SECOND.equals(type)) {
        result = curr.plusSeconds(interval);
    }
    return result;
}
 
Example 3
Source File: TestDateTimeZone.java    From joda-time-android with Apache License 2.0 6 votes vote down vote up
@Test
public void testDublin() {
    DateTimeZone zone = DateTimeZone.forID("Europe/Dublin");
    DateTime winter = new DateTime(2018, 1, 1, 0, 0, 0, 0, zone);
    assertEquals(0, zone.getStandardOffset(winter.getMillis()));
    assertEquals(0, zone.getOffset(winter.getMillis()));
    assertEquals(true, zone.isStandardOffset(winter.getMillis()));
    assertEquals("Greenwich Mean Time", zone.getName(winter.getMillis()));
    assertEquals("GMT", zone.getNameKey(winter.getMillis()));

    DateTime summer = winter.plusMonths(6);
    assertEquals(0, zone.getStandardOffset(summer.getMillis()));
    assertEquals(3600000, zone.getOffset(summer.getMillis()));
    assertEquals(false, zone.isStandardOffset(summer.getMillis()));
    assertEquals(true, zone.getName(summer.getMillis()).startsWith("Irish "));
    assertEquals("IST", zone.getNameKey(summer.getMillis()));
}
 
Example 4
Source File: ArchivedFormPurgeTest.java    From commcare-android with Apache License 2.0 6 votes vote down vote up
/**
 * Ensure that the correct number of forms are purged given different
 * validity ranges
 */
@Test
public void testSavedFormPurge() {
    int SAVED_FORM_COUNT = 5;

    String firstFormCompletionDate = "Mon Oct 05 16:17:01 -0400 2015";
    DateTimeFormatter dtf = DateTimeFormat.forPattern("EEE MMM dd HH:mm:ss Z yyyy");
    DateTime startTestDate = dtf.parseDateTime(firstFormCompletionDate);

    DateTime twoMonthsLater = startTestDate.plusMonths(2);
    assertEquals("Only 1 form should remain if we're 2 months past the 1st form's create date.",
            SAVED_FORM_COUNT - 1,
            PurgeStaleArchivedFormsTask.getSavedFormsToPurge(twoMonthsLater).size());

    DateTime twentyYearsLater = startTestDate.plusYears(20);
    assertEquals("All forms should be purged if we are way in the future.",
            SAVED_FORM_COUNT,
            PurgeStaleArchivedFormsTask.getSavedFormsToPurge(twentyYearsLater).size());

    assertEquals("When the time is the 1st form's creation time, no forms should be purged",
            0,
            PurgeStaleArchivedFormsTask.getSavedFormsToPurge(startTestDate).size());
}
 
Example 5
Source File: MeasureDataCalendarQueryAction.java    From bamboobsc with Apache License 2.0 6 votes vote down vote up
private String handlerDate() throws Exception {
	String dateStr = this.getFields().get("date");
	String frequency = this.getFields().get("frequency");
	String dateStatus = this.getFields().get("dateStatus");
	DateTime dateTime = new DateTime(dateStr);
	if ("-1".equals(dateStatus)) { // 上一個
		if (BscMeasureDataFrequency.FREQUENCY_DAY.equals(frequency) || BscMeasureDataFrequency.FREQUENCY_WEEK.equals(frequency) ) { // 上一個月
			dateTime = dateTime.plusMonths(-1);
		} else { // 上一個年
			dateTime = dateTime.plusYears(-1);
		}			
	}
	if ("1".equals(dateStatus)) { // 下一個
		if (BscMeasureDataFrequency.FREQUENCY_DAY.equals(frequency) || BscMeasureDataFrequency.FREQUENCY_WEEK.equals(frequency) ) { // 下一個月
			dateTime = dateTime.plusMonths(1);
		} else { // 下一個年
			dateTime = dateTime.plusYears(1);
		}			
	}		
	return dateTime.toString("yyyy-MM-dd");
}
 
Example 6
Source File: DateTimeFunctions.java    From jasperreports with GNU Lesser General Public License v3.0 6 votes vote down vote up
/**
 * Returns a date a number of months away.
 */
@Function("EDATE")
@FunctionParameters({
	@FunctionParameter("dateObject"),
	@FunctionParameter("months")})
public Date EDATE(Object dateObject, Integer months){
	Date convertedDate = convertDateObject(dateObject);
	if(convertedDate==null){
		logCannotConvertToDate();
		return null;
	}
	else{
		DateTime dt=new DateTime(convertedDate);
		dt = dt.plusMonths(months);
		return dt.toDate();
	}
}
 
Example 7
Source File: DateTimePeriod.java    From cloudhopper-commons with Apache License 2.0 6 votes vote down vote up
/**
 * Converts this period to a list of month periods.  Partial months will not be
 * included.  For example, a period of "2009" will return a list
 * of 12 months - one for each month in 2009.  On the other hand, a period
 * of "January 20, 2009" would return an empty list since partial
 * months are not included.
 * @return A list of month periods contained within this period
 */
public List<DateTimePeriod> toMonths() {
    ArrayList<DateTimePeriod> list = new ArrayList<DateTimePeriod>();

    // default "current" month to start datetime
    DateTime currentStart = getStart();
    // calculate "next" month
    DateTime nextStart = currentStart.plusMonths(1);
    // continue adding until we've reached the end
    while (nextStart.isBefore(getEnd()) || nextStart.isEqual(getEnd())) {
        // its okay to add the current
        list.add(new DateTimeMonth(currentStart, nextStart));
        // increment both
        currentStart = nextStart;
        nextStart = currentStart.plusMonths(1);
    }

    return list;
}
 
Example 8
Source File: ChronologyBasedCalendar.java    From dhis2-core with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
private DateInterval toMonthIsoInterval( DateTimeUnit dateTimeUnit, int offset, int length )
{
    DateTime from = dateTimeUnit.toJodaDateTime( chronology );

    if ( offset > 0 )
    {
        from = from.plusMonths( offset );
    }
    else if ( offset < 0 )
    {
        from = from.minusMonths( -offset );
    }

    DateTime to = new DateTime( from ).plusMonths( length ).minusDays( 1 );

    DateTimeUnit fromDateTimeUnit = DateTimeUnit.fromJodaDateTime( from );
    DateTimeUnit toDateTimeUnit = DateTimeUnit.fromJodaDateTime( to );

    fromDateTimeUnit.setDayOfWeek( isoWeekday( fromDateTimeUnit ) );
    toDateTimeUnit.setDayOfWeek( isoWeekday( toDateTimeUnit ) );

    return new DateInterval( toIso( fromDateTimeUnit ), toIso( toDateTimeUnit ), DateIntervalType.ISO8601_MONTH );
}
 
Example 9
Source File: UpdateTldCommandTest.java    From nomulus with Apache License 2.0 6 votes vote down vote up
@Test
public void testSuccess_tldStateTransitions() throws Exception {
  DateTime sunriseStart = now;
  DateTime quietPeriodStart = sunriseStart.plusMonths(2);
  DateTime gaStart = quietPeriodStart.plusWeeks(1);
  runCommandForced(
      String.format(
          "--tld_state_transitions=%s=PREDELEGATION,%s=START_DATE_SUNRISE,%s=QUIET_PERIOD,"
              + "%s=GENERAL_AVAILABILITY",
          START_OF_TIME, sunriseStart, quietPeriodStart, gaStart),
      "xn--q9jyb4c");

  Registry registry = Registry.get("xn--q9jyb4c");
  assertThat(registry.getTldState(sunriseStart.minusMillis(1))).isEqualTo(PREDELEGATION);
  assertThat(registry.getTldState(sunriseStart)).isEqualTo(START_DATE_SUNRISE);
  assertThat(registry.getTldState(sunriseStart.plusMillis(1))).isEqualTo(START_DATE_SUNRISE);
  assertThat(registry.getTldState(quietPeriodStart.minusMillis(1))).isEqualTo(START_DATE_SUNRISE);
  assertThat(registry.getTldState(quietPeriodStart)).isEqualTo(QUIET_PERIOD);
  assertThat(registry.getTldState(quietPeriodStart.plusMillis(1))).isEqualTo(QUIET_PERIOD);
  assertThat(registry.getTldState(gaStart.minusMillis(1))).isEqualTo(QUIET_PERIOD);
  assertThat(registry.getTldState(gaStart)).isEqualTo(GENERAL_AVAILABILITY);
  assertThat(registry.getTldState(gaStart.plusMillis(1))).isEqualTo(GENERAL_AVAILABILITY);
  assertThat(registry.getTldState(END_OF_TIME)).isEqualTo(GENERAL_AVAILABILITY);
}
 
Example 10
Source File: SamlFederationResourceTest.java    From secure-data-service with Apache License 2.0 5 votes vote down vote up
@Test
public void processArtifactBindingInvalidCondition() throws URISyntaxException {
    setRealm(false);
    HttpServletRequest request = Mockito.mock(HttpServletRequest.class);
    UriInfo uriInfo = Mockito.mock(UriInfo.class);

    URI uri = new URI(issuerString);

    Mockito.when(uriInfo.getRequestUri()).thenReturn(uri);
    Mockito.when(uriInfo.getAbsolutePath()).thenReturn(uri);

    Mockito.when(request.getParameter("SAMLart")).thenReturn("AAQAAjh3bwgbBZ+LiIx3/RVwDGy0aRUu+xxuNtTZVbFofgZZVCKJQwQNQ7Q=");
    Mockito.when(request.getParameter("RelayState")).thenReturn("My Realm");

    List<Assertion> assertions = new ArrayList<Assertion>();

    DateTimeFormatter fmt = DateTimeFormat.forPattern("MM/dd/yyyy");
    DateTime datetime = DateTime.now();
    datetime = datetime.plusMonths(2) ;
    Assertion assertion = createAssertion(datetime.toString(fmt), "01/10/2011", issuerString);
    assertions.add(assertion);
    Mockito.when(samlHelper.getAssertion(Mockito.any(org.opensaml.saml2.core.Response.class), Mockito.any(KeyStore.PrivateKeyEntry.class))).thenReturn(assertion);

    //invalid condition
    expectedException.expect(APIAccessDeniedException.class);
    expectedException.expectMessage("Authorization could not be verified.");
    resource.processArtifactBinding(request, uriInfo);

    //null subject
    Mockito.when(assertion.getSubject()).thenReturn(null);
    resource.processArtifactBinding(request, uriInfo);

    //invalid subject
    assertions.clear();
    assertions.add(createAssertion("01/10/2011", datetime.toString(fmt),  issuerString));
    resource.processArtifactBinding(request, uriInfo);
}
 
Example 11
Source File: FrameworkUtils.java    From data-polygamy with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
public static DateTime addTime(int tempRes, int increment, DateTime start) {
    
    DateTime d = null;
    
    switch(tempRes) {
    case FrameworkUtils.HOUR:
        d = start.plusHours(increment);
        break;
    case FrameworkUtils.DAY:
        d = start.plusDays(increment);
        break;
    case FrameworkUtils.WEEK:
        d = start.plusWeeks(increment);
        break;
    case FrameworkUtils.MONTH:
        d = start.plusMonths(increment);
        break;
    case FrameworkUtils.YEAR:
        d = start.plusYears(increment);
        break;
    default:
        d = start.plusHours(increment);
        break;
    }
    
    return d;
    
}
 
Example 12
Source File: FrameworkUtils.java    From data-polygamy with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
public static int addTimeSteps(int tempRes, int increment, DateTime start) {
    
    DateTime d;
    
    switch(tempRes) {
    case FrameworkUtils.HOUR:
        d = start.plusHours(increment);
        break;
    case FrameworkUtils.DAY:
        d = start.plusDays(increment);
        break;
    case FrameworkUtils.WEEK:
        d = start.plusWeeks(increment);
        break;
    case FrameworkUtils.MONTH:
        d = start.plusMonths(increment);
        break;
    case FrameworkUtils.YEAR:
        d = start.plusYears(increment);
        break;
    default:
        d = start.plusHours(increment);
        break;
    }
    
    return (int) (d.getMillis()/1000);
    
}
 
Example 13
Source File: GenerateAllocationTokensCommandTest.java    From nomulus with Apache License 2.0 5 votes vote down vote up
@Test
public void testSuccess_promotionToken() throws Exception {
  DateTime promoStart = DateTime.now(UTC);
  DateTime promoEnd = promoStart.plusMonths(1);
  runCommand(
      "--number", "1",
      "--prefix", "promo",
      "--type", "UNLIMITED_USE",
      "--allowed_client_ids", "TheRegistrar,NewRegistrar",
      "--allowed_tlds", "tld,example",
      "--discount_fraction", "0.5",
      "--token_status_transitions",
          String.format(
              "\"%s=NOT_STARTED,%s=VALID,%s=ENDED\"", START_OF_TIME, promoStart, promoEnd));
  assertAllocationTokens(
      new AllocationToken.Builder()
          .setToken("promo123456789ABCDEFG")
          .setTokenType(UNLIMITED_USE)
          .setAllowedClientIds(ImmutableSet.of("TheRegistrar", "NewRegistrar"))
          .setAllowedTlds(ImmutableSet.of("tld", "example"))
          .setDiscountFraction(0.5)
          .setTokenStatusTransitions(
              ImmutableSortedMap.<DateTime, TokenStatus>naturalOrder()
                  .put(START_OF_TIME, TokenStatus.NOT_STARTED)
                  .put(promoStart, TokenStatus.VALID)
                  .put(promoEnd, TokenStatus.ENDED)
                  .build())
          .build());
}
 
Example 14
Source File: CalendarWindows.java    From beam with Apache License 2.0 5 votes vote down vote up
@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());
}
 
Example 15
Source File: TimeExpressionUtils.java    From liteflow with Apache License 2.0 5 votes vote down vote up
/**
     * 按某个时间单位添加时间
     * @param dateTime
     * @param n
     * @param timeUnit
     * @return
     */
    public static DateTime calculateTime(DateTime dateTime, int n, TimeUnit timeUnit) {

        DateTime addedDateTime = null;
        switch (timeUnit){
//            case SECOND:
//                addedDateTime = dateTime.plusSeconds(n);
//                break;
            case MINUTE:
                addedDateTime = dateTime.plusMinutes(n);
                break;
            case HOUR:
                addedDateTime = dateTime.plusHours(n);
                break;
            case DAY:
                addedDateTime = dateTime.plusDays(n);
                break;
            case WEEK:
                addedDateTime = dateTime.plusWeeks(n);
                break;
            case MONTH:
                addedDateTime = dateTime.plusMonths(n);
                break;
            case YEAR:
                addedDateTime = dateTime.plusYears(n);
                break;
        }

        return addedDateTime;
    }
 
Example 16
Source File: DateTimePeriod.java    From cloudhopper-commons with Apache License 2.0 4 votes vote down vote up
static public DateTimePeriod createMonth(DateTime start) {
    DateTime end = start.plusMonths(1);
    return new DateTimeMonth(start, end);
}
 
Example 17
Source File: JodatimeUtilsTest.java    From onetwo with Apache License 2.0 4 votes vote down vote up
@Test
public void testDate(){
	/*LocalDateTime fromDate = new LocalDateTime(new Date());
	String str = fromDate.toString("yyyy-MM-dd HH:mm:ss.SSS");
	System.out.println("str:"+str);
	LocalTime localTime = fromDate.toLocalTime();
	System.out.println("localTime:"+localTime.toString());
	System.out.println("localTime:"+localTime.toString("yyyy-MM-dd HH:mm:ss"));
	System.out.println("toDateTimeToday:"+localTime.toDateTimeToday().toDate().toLocaleString());
	
	fromDate = new LocalDateTime(new Date());
	fromDate = fromDate.year().setCopy(1970).monthOfYear().setCopy(1).dayOfMonth().setCopy(1);
	System.out.println("fromDate:"+fromDate.toString("yyyy-MM-dd HH:mm:ss"));
	
	Calendar cal = Calendar.getInstance();
	cal.setTime(new Date());
	cal.set(1970, 0, 1);
	System.out.println("cal:"+cal.getTime().toLocaleString());*/
	
	DateTime dt = DateTime.now().millisOfDay().withMinimumValue();
	System.out.println(JodatimeUtils.formatDateTime(dt.toDate()));
	dt = dt.millisOfDay().withMaximumValue();
	System.out.println(JodatimeUtils.formatDateTime(dt.toDate()));
	System.out.println(JodatimeUtils.formatDateTime(JodatimeUtils.atEndOfDate(dt.toDate()).toDate()));
	
	DateTime date = JodatimeUtils.parse("2015-03-18");
	System.out.println("date: " + date.getDayOfMonth());
	Assert.assertEquals(18, date.getDayOfMonth());
	
	date = JodatimeUtils.parse("2016-04-13");
	System.out.println("week: " + date.getWeekOfWeekyear());
	Assert.assertEquals(15, date.getWeekOfWeekyear());
	
	DateTime dateTime = DateTime.parse("2016-04-13");
	System.out.println("dateTime:"+dateTime);
	DateTime start = dateTime.dayOfWeek().withMinimumValue();
	DateTime end = start.plusWeeks(1);
	System.out.println("start:"+start);
	System.out.println("end:"+end);
	Assert.assertEquals("2016-04-11", start.toString("yyyy-MM-dd"));
	Assert.assertEquals("2016-04-18", end.toString("yyyy-MM-dd"));


	start = dateTime.dayOfMonth().withMinimumValue();
	end = start.plusMonths(1);
	System.out.println("start:"+start);
	System.out.println("end:"+end);
	Assert.assertEquals("2016-04-01", start.toString("yyyy-MM-dd"));
	Assert.assertEquals("2016-05-01", end.toString("yyyy-MM-dd"));

	start = dateTime.dayOfYear().withMinimumValue();
	end = start.plusYears(1);
	System.out.println("start:"+start);
	System.out.println("end:"+end);
	Assert.assertEquals("2016-01-01", start.toString("yyyy-MM-dd"));
	Assert.assertEquals("2017-01-01", end.toString("yyyy-MM-dd"));
}
 
Example 18
Source File: DateUtils.java    From liteflow with Apache License 2.0 4 votes vote down vote up
/**
 * 获取下个月
 * @param date
 * @return
 */
public static Date getNextMonth(Date date) {
    DateTime dateTime = new DateTime(date);
    dateTime = dateTime.plusMonths(1);
    return dateTime.toDate();
}
 
Example 19
Source File: DatePlusMonths.java    From levelup-java-examples with Apache License 2.0 3 votes vote down vote up
@Test
public void add_months_to_date_in_java_joda () {
	
	DateTime superBowlXLV = new DateTime(2011, 2, 6, 0, 0, 0, 0);
	DateTime sippinFruityDrinksInMexico = superBowlXLV.plusMonths(1);

	DateTimeFormatter fmt = DateTimeFormat.forPattern("MM/dd/yyyy HH:mm:ss z");
	
	logger.info(superBowlXLV.toString(fmt));
	logger.info(sippinFruityDrinksInMexico.toString(fmt));

	assertTrue(sippinFruityDrinksInMexico.isAfter(superBowlXLV));
}
 
Example 20
Source File: SamlFederationResourceTest.java    From secure-data-service with Apache License 2.0 3 votes vote down vote up
private Assertion createAssertion(String conditionNotBefore,  String subjectNotBefore, String recipient) {
    Assertion assertion = Mockito.mock(Assertion.class);

    Conditions conditions = Mockito.mock(Conditions.class);

    DateTimeFormatter fmt = DateTimeFormat.forPattern("MM/dd/yyyy");

    DateTime datetime = DateTime.now();
    datetime = datetime.plusMonths(1) ;

    Mockito.when(conditions.getNotBefore()).thenReturn(DateTime.parse(conditionNotBefore, fmt));
    Mockito.when(conditions.getNotOnOrAfter()).thenReturn(DateTime.parse(datetime.toString(fmt), fmt));

    Subject subject = Mockito.mock(Subject.class);
    SubjectConfirmationData subjectConfirmationData = Mockito.mock(SubjectConfirmationData.class);

    SubjectConfirmation subjectConfirmation = Mockito.mock(SubjectConfirmation.class);
    Mockito.when(subjectConfirmation.getSubjectConfirmationData()).thenReturn(subjectConfirmationData);

    ArrayList<SubjectConfirmation> res = new ArrayList<SubjectConfirmation>();
    res.add(subjectConfirmation);

    Mockito.when(subject.getSubjectConfirmations()).thenReturn(res);

    Mockito.when(subjectConfirmationData.getNotBefore()).thenReturn(DateTime.parse(subjectNotBefore, fmt));
    Mockito.when(subjectConfirmationData.getNotOnOrAfter()).thenReturn(DateTime.parse(datetime.toString(fmt), fmt));
    Mockito.when(subjectConfirmationData.getRecipient()).thenReturn(recipient);

    Mockito.when(assertion.getConditions()).thenReturn(conditions);
    Mockito.when(assertion.getSubject()).thenReturn(subject);

    return assertion;
}