Example usage for org.joda.time DateTime plusHours

List of usage examples for org.joda.time DateTime plusHours

Introduction

In this page you can find the example usage for org.joda.time DateTime plusHours.

Prototype

public DateTime plusHours(int hours) 

Source Link

Document

Returns a copy of this datetime plus the specified number of hours.

Usage

From source file:com.cisco.dvbu.ps.utils.date.DateAddTimestamp.java

License:Open Source License

/**
 * Called to invoke the stored procedure.  Will only be called a
 * single time per instance.  Can throw CustomProcedureException or
 * SQLException if there is an error during invoke.
 *///  ww  w.j av a 2s .  co m
@Override
public void invoke(Object[] inputValues) throws CustomProcedureException, SQLException {
    Timestamp startDate = null;
    Calendar startCal = null;
    DateTime startDateTime = null;
    DateTime endDateTime = null;
    String datePart = null;
    int dateLength = 0;

    try {
        result = null;
        if (inputValues[0] == null || inputValues[1] == null || inputValues[2] == null) {
            return;
        }

        datePart = (String) inputValues[0];
        dateLength = (Integer) inputValues[1];

        startDate = (Timestamp) inputValues[2];
        startCal = Calendar.getInstance();
        startCal.setTime(startDate);
        startDateTime = new DateTime(startCal.get(Calendar.YEAR), startCal.get(Calendar.MONTH) + 1,
                startCal.get(Calendar.DAY_OF_MONTH), startCal.get(Calendar.HOUR_OF_DAY),
                startCal.get(Calendar.MINUTE), startCal.get(Calendar.SECOND),
                startCal.get(Calendar.MILLISECOND));

        if (datePart.equalsIgnoreCase("second")) {
            endDateTime = startDateTime.plusSeconds(dateLength);
        }

        if (datePart.equalsIgnoreCase("minute")) {
            endDateTime = startDateTime.plusMinutes(dateLength);
        }

        if (datePart.equalsIgnoreCase("hour")) {
            endDateTime = startDateTime.plusHours(dateLength);
        }

        if (datePart.equalsIgnoreCase("day")) {
            endDateTime = startDateTime.plusDays(dateLength);
        }

        if (datePart.equalsIgnoreCase("week")) {
            endDateTime = startDateTime.plusWeeks(dateLength);
        }

        if (datePart.equalsIgnoreCase("month")) {
            endDateTime = startDateTime.plusMonths(dateLength);
        }

        if (datePart.equalsIgnoreCase("year")) {
            endDateTime = startDateTime.plusYears(dateLength);
        }

        result = new Timestamp(endDateTime.toDate().getTime());
    } catch (Throwable t) {
        throw new CustomProcedureException(t);
    }
}

From source file:com.cloudhopper.commons.util.time.DateTimePeriod.java

License:Apache License

/**
 * Converts this period to a list of hour periods.  Partial hours will not be
 * included.  For example, a period of "January 20, 2009" will return a list
 * of 24 hours - one for each hour on January 20, 2009.  On the other hand,
 * a period of "January 20, 2009 13:10" would return an empty list since partial
 * hours are not included.// w  w w  . ja  va 2s . c om
 * @return A list of hour periods contained within this period
 */
public List<DateTimePeriod> toHours() {
    ArrayList<DateTimePeriod> list = new ArrayList<DateTimePeriod>();

    // default "current" hour to start datetime
    DateTime currentStart = getStart();
    // calculate "next" hour
    DateTime nextStart = currentStart.plusHours(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 DateTimeHour(currentStart, nextStart));
        // increment both
        currentStart = nextStart;
        nextStart = currentStart.plusHours(1);
    }

    return list;
}

From source file:com.cloudhopper.commons.util.time.DateTimePeriod.java

License:Apache License

static public DateTimePeriod createHour(DateTime start) {
    DateTime end = start.plusHours(1);
    return new DateTimeHour(start, end);
}

From source file:com.cronutils.model.time.ExecutionTime.java

License:Apache License

/**
 * If date is not match, will return next closest match.
 * If date is match, will return this date.
 * @param date - reference DateTime instance - never null;
 * @return DateTime instance, never null. Value obeys logic specified above.
 * @throws NoSuchValueException//from  w w w .  j a  va 2s. c o m
 */
DateTime nextClosestMatch(DateTime date) throws NoSuchValueException {
    List<Integer> year = yearsValueGenerator.generateCandidates(date.getYear(), date.getYear());
    TimeNode days = null;
    int lowestMonth = months.getValues().get(0);
    int lowestHour = hours.getValues().get(0);
    int lowestMinute = minutes.getValues().get(0);
    int lowestSecond = seconds.getValues().get(0);

    NearestValue nearestValue;
    DateTime newDate;
    if (year.isEmpty()) {
        int newYear = yearsValueGenerator.generateNextValue(date.getYear());
        days = generateDays(cronDefinition, new DateTime(newYear, lowestMonth, 1, 0, 0));
        return initDateTime(yearsValueGenerator.generateNextValue(date.getYear()), lowestMonth,
                days.getValues().get(0), lowestHour, lowestMinute, lowestSecond, date.getZone());
    }
    if (!months.getValues().contains(date.getMonthOfYear())) {
        nearestValue = months.getNextValue(date.getMonthOfYear(), 0);
        int nextMonths = nearestValue.getValue();
        if (nearestValue.getShifts() > 0) {
            newDate = new DateTime(date.getYear(), 1, 1, 0, 0, 0, date.getZone())
                    .plusYears(nearestValue.getShifts());
            return nextClosestMatch(newDate);
        }
        if (nearestValue.getValue() < date.getMonthOfYear()) {
            date = date.plusYears(1);
        }
        days = generateDays(cronDefinition, new DateTime(date.getYear(), nextMonths, 1, 0, 0));
        return initDateTime(date.getYear(), nextMonths, days.getValues().get(0), lowestHour, lowestMinute,
                lowestSecond, date.getZone());
    }
    days = generateDays(cronDefinition, date);
    if (!days.getValues().contains(date.getDayOfMonth())) {
        nearestValue = days.getNextValue(date.getDayOfMonth(), 0);
        if (nearestValue.getShifts() > 0) {
            newDate = new DateTime(date.getYear(), date.getMonthOfYear(), 1, 0, 0, 0, date.getZone())
                    .plusMonths(nearestValue.getShifts());
            return nextClosestMatch(newDate);
        }
        if (nearestValue.getValue() < date.getDayOfMonth()) {
            date = date.plusMonths(1);
        }
        return initDateTime(date.getYear(), date.getMonthOfYear(), nearestValue.getValue(), lowestHour,
                lowestMinute, lowestSecond, date.getZone());
    }
    if (!hours.getValues().contains(date.getHourOfDay())) {
        nearestValue = hours.getNextValue(date.getHourOfDay(), 0);
        int nextHours = nearestValue.getValue();
        if (nearestValue.getShifts() > 0) {
            newDate = new DateTime(date.getYear(), date.getMonthOfYear(), date.getDayOfMonth(), 0, 0, 0,
                    date.getZone()).plusDays(nearestValue.getShifts());
            return nextClosestMatch(newDate);
        }
        if (nearestValue.getValue() < date.getHourOfDay()) {
            date = date.plusDays(1);
        }
        return initDateTime(date.getYear(), date.getMonthOfYear(), date.getDayOfMonth(), nextHours,
                lowestMinute, lowestSecond, date.getZone());
    }
    if (!minutes.getValues().contains(date.getMinuteOfHour())) {
        nearestValue = minutes.getNextValue(date.getMinuteOfHour(), 0);
        int nextMinutes = nearestValue.getValue();
        if (nearestValue.getShifts() > 0) {
            newDate = new DateTime(date.getYear(), date.getMonthOfYear(), date.getDayOfMonth(),
                    date.getHourOfDay(), 0, 0, date.getZone()).plusHours(nearestValue.getShifts());
            return nextClosestMatch(newDate);
        }
        if (nearestValue.getValue() < date.getMinuteOfHour()) {
            date = date.plusHours(1);
        }
        return initDateTime(date.getYear(), date.getMonthOfYear(), date.getDayOfMonth(), date.getHourOfDay(),
                nextMinutes, lowestSecond, date.getZone());
    }
    if (!seconds.getValues().contains(date.getSecondOfMinute())) {
        nearestValue = seconds.getNextValue(date.getSecondOfMinute(), 0);
        int nextSeconds = nearestValue.getValue();
        if (nearestValue.getShifts() > 0) {
            newDate = new DateTime(date.getYear(), date.getMonthOfYear(), date.getDayOfMonth(),
                    date.getHourOfDay(), date.getMinuteOfHour(), 0, date.getZone())
                            .plusMinutes(nearestValue.getShifts());
            return nextClosestMatch(newDate);
        }
        if (nearestValue.getValue() < date.getSecondOfMinute()) {
            date = date.plusMinutes(1);
        }
        return initDateTime(date.getYear(), date.getMonthOfYear(), date.getDayOfMonth(), date.getHourOfDay(),
                date.getMinuteOfHour(), nextSeconds, date.getZone());
    }
    return date;
}

From source file:com.enitalk.configs.DateCache.java

public NavigableSet<DateTime> days(JsonNode tree, String tz, JsonNode teacherNode) {
    ConcurrentSkipListSet<DateTime> dates = new ConcurrentSkipListSet<>();

    Iterator<JsonNode> els = tree.elements();
    DateTimeZone dz = DateTimeZone.forID(tz);
    DateTimeFormatter hour = DateTimeFormat.forPattern("HH:mm").withZone(dz);

    DateTime today = DateTime.now().millisOfDay().setCopy(0);
    while (els.hasNext()) {

        JsonNode el = els.next();//  w ww. j  ava2 s.co  m
        String day = el.path("day").asText();

        boolean plus = today.getDayOfWeek() > days.get(day);
        if (el.has("start") && el.has("end")) {
            DateTime start = hour.parseDateTime(el.path("start").asText()).dayOfMonth()
                    .setCopy(today.getDayOfMonth()).monthOfYear().setCopy(today.getMonthOfYear()).year()
                    .setCopy(today.getYear()).withDayOfWeek(days.get(day)).plusWeeks(plus ? 1 : 0);
            DateTime end = hour.parseDateTime(el.path("end").asText()).dayOfMonth()
                    .setCopy(today.getDayOfMonth()).monthOfYear().setCopy(today.getMonthOfYear()).year()
                    .setCopy(today.getYear()).withDayOfWeek(days.get(day)).plusWeeks(plus ? 1 : 0);

            Hours hours = Hours.hoursBetween(start, end);
            int hh = hours.getHours() + 1;

            while (hh-- > 0) {
                dates.add(start.plusHours(hh).toDateTime(DateTimeZone.UTC));
            }
        } else {
            List<String> datesAv = jackson.convertValue(el.path("times"), List.class);
            logger.info("Array of dates {} {}", datesAv, day);

            datesAv.forEach((String dd) -> {
                DateTime date = hour.parseDateTime(dd).dayOfMonth().setCopy(today.getDayOfMonth()).monthOfYear()
                        .setCopy(today.getMonthOfYear()).year().setCopy(today.getYear())
                        .withDayOfWeek(days.get(day)).plusWeeks(plus ? 1 : 0);
                dates.add(date.toDateTime(DateTimeZone.UTC));
            });

        }

    }

    final TreeSet<DateTime> addWeek = new TreeSet<>();
    for (int i = 1; i < 2; i++) {
        for (DateTime e : dates) {
            addWeek.add(e.plusWeeks(i));

        }
    }

    dates.addAll(addWeek);

    DateTime nowUtc = DateTime.now().toDateTime(DateTimeZone.UTC);
    nowUtc = nowUtc.plusHours(teacherNode.path("notice").asInt(2));

    NavigableSet<DateTime> ss = dates.tailSet(nowUtc, true);

    return ss;

}

From source file:com.enonic.cms.server.service.admin.mvc.controller.ResourceController.java

License:Open Source License

/**
 * Handle the request.//from   ww w  .jav  a2s .  c  o m
 */
protected ModelAndView handleRequestInternal(HttpServletRequest request, HttpServletResponse response)
        throws Exception {
    String path = urlPathHelper.getPathWithinApplication(request);
    Resource resource = this.resourceLoader.getResource(path);

    if (resource.exists()) {
        DateTime now = new DateTime();
        DateTime expirationDate = now.plusHours(1);

        HttpCacheControlSettings cacheControlSettings = new HttpCacheControlSettings();
        cacheControlSettings.maxAgeSecondsToLive = new Interval(now, expirationDate).toDurationMillis() / 1000;
        cacheControlSettings.publicAccess = true;

        HttpServletUtil.setDateHeader(response, now.toDate());
        HttpServletUtil.setExpiresHeader(response, expirationDate.toDate());
        HttpServletUtil.setCacheControl(response, cacheControlSettings);

        serveResourceToResponse(request, response, resource);
    } else {
        response.sendError(HttpServletResponse.SC_NOT_FOUND);
    }

    return null;
}

From source file:com.ext.portlet.epsos.EpsosHelperService.java

public static Assertion createAssertion(String username, String role, String organization,
        String organizationId, String facilityType, String purposeOfUse, String xspaLocality,
        java.util.Vector permissions) {
    // assertion/*from w w w  .  ja  v a 2  s  . c  o  m*/
    Assertion assertion = null;
    try {
        DefaultBootstrap.bootstrap();
        XMLObjectBuilderFactory builderFactory = Configuration.getBuilderFactory();

        SAMLObjectBuilder<Assertion> builder = (SAMLObjectBuilder<Assertion>) builderFactory
                .getBuilder(Assertion.DEFAULT_ELEMENT_NAME);

        // Create the NameIdentifier
        SAMLObjectBuilder nameIdBuilder = (SAMLObjectBuilder) builderFactory
                .getBuilder(NameID.DEFAULT_ELEMENT_NAME);
        NameID nameId = (NameID) nameIdBuilder.buildObject();
        nameId.setValue(username);
        //nameId.setNameQualifier(strNameQualifier);
        nameId.setFormat(NameID.UNSPECIFIED);

        assertion = create(Assertion.class, Assertion.DEFAULT_ELEMENT_NAME);

        String assId = "_" + UUID.randomUUID();
        assertion.setID(assId);
        assertion.setVersion(SAMLVersion.VERSION_20);
        assertion.setIssueInstant(new org.joda.time.DateTime().minusHours(3));

        Subject subject = create(Subject.class, Subject.DEFAULT_ELEMENT_NAME);
        assertion.setSubject(subject);
        subject.setNameID(nameId);

        //Create and add Subject Confirmation
        SubjectConfirmation subjectConf = create(SubjectConfirmation.class,
                SubjectConfirmation.DEFAULT_ELEMENT_NAME);
        subjectConf.setMethod(SubjectConfirmation.METHOD_SENDER_VOUCHES);
        assertion.getSubject().getSubjectConfirmations().add(subjectConf);

        //Create and add conditions
        Conditions conditions = create(Conditions.class, Conditions.DEFAULT_ELEMENT_NAME);
        org.joda.time.DateTime now = new org.joda.time.DateTime();
        conditions.setNotBefore(now.minusMinutes(1));
        conditions.setNotOnOrAfter(now.plusHours(2)); // According to Spec
        assertion.setConditions(conditions);

        //           AudienceRestriction ar = create(AudienceRestriction.class,AudienceRestriction.DEFAULT_ELEMENT_NAME);
        //           Audience aud = create(Audience.class,Audience.DEFAULT_ELEMENT_NAME);
        //           aud.setAudienceURI("aaa");

        //           conditions.s

        Issuer issuer = new IssuerBuilder().buildObject();
        issuer.setValue("urn:idp:countryB");
        issuer.setNameQualifier("urn:epsos:wp34:assertions");
        assertion.setIssuer(issuer);

        //Add and create the authentication statement
        AuthnStatement authStmt = create(AuthnStatement.class, AuthnStatement.DEFAULT_ELEMENT_NAME);
        authStmt.setAuthnInstant(now.minusHours(2));
        assertion.getAuthnStatements().add(authStmt);

        //Create and add AuthnContext
        AuthnContext ac = create(AuthnContext.class, AuthnContext.DEFAULT_ELEMENT_NAME);
        AuthnContextClassRef accr = create(AuthnContextClassRef.class,
                AuthnContextClassRef.DEFAULT_ELEMENT_NAME);
        accr.setAuthnContextClassRef(AuthnContext.PASSWORD_AUTHN_CTX);
        ac.setAuthnContextClassRef(accr);
        authStmt.setAuthnContext(ac);

        AttributeStatement attrStmt = create(AttributeStatement.class, AttributeStatement.DEFAULT_ELEMENT_NAME);

        // XSPA Subject
        Attribute attrPID = createAttribute(builderFactory, "XSPA subject",
                "urn:oasis:names:tc:xacml:1.0:subject:subject-id", username, "", "");
        attrStmt.getAttributes().add(attrPID);
        // XSPA Role        
        Attribute attrPID_1 = createAttribute(builderFactory, "XSPA role",
                "urn:oasis:names:tc:xacml:2.0:subject:role", role, "", "");
        attrStmt.getAttributes().add(attrPID_1);
        // HITSP Clinical Speciality
        /*        Attribute attrPID_2 = createAttribute(builderFactory,"HITSP Clinical Speciality",
         "urn:epsos:names:wp3.4:subject:clinical-speciality",role,"","");
                attrStmt.getAttributes().add(attrPID_2);
                */
        // XSPA Organization
        Attribute attrPID_3 = createAttribute(builderFactory, "XSPA Organization",
                "urn:oasis:names:tc:xspa:1.0:subject:organization", organization, "", "");
        attrStmt.getAttributes().add(attrPID_3);
        // XSPA Organization ID
        Attribute attrPID_4 = createAttribute(builderFactory, "XSPA Organization ID",
                "urn:oasis:names:tc:xspa:1.0:subject:organization-id", organizationId, "AA", "");
        attrStmt.getAttributes().add(attrPID_4);

        //           // On behalf of
        //           Attribute attrPID_4 = createAttribute(builderFactory,"OnBehalfOf",
        //         "urn:epsos:names:wp3.4:subject:on-behalf-of",organizationId,role,"");
        //         attrStmt.getAttributes().add(attrPID_4);

        // epSOS Healthcare Facility Type
        Attribute attrPID_5 = createAttribute(builderFactory, "epSOS Healthcare Facility Type",
                "urn:epsos:names:wp3.4:subject:healthcare-facility-type", facilityType, "", "");
        attrStmt.getAttributes().add(attrPID_5);
        // XSPA Purpose of Use
        Attribute attrPID_6 = createAttribute(builderFactory, "XSPA Purpose Of Use",
                "urn:oasis:names:tc:xspa:1.0:subject:purposeofuse", purposeOfUse, "", "");
        attrStmt.getAttributes().add(attrPID_6);
        // XSPA Locality
        Attribute attrPID_7 = createAttribute(builderFactory, "XSPA Locality",
                "urn:oasis:names:tc:xspa:1.0:environment:locality", xspaLocality, "", "");
        attrStmt.getAttributes().add(attrPID_7);
        // HL7 Permissions
        Attribute attrPID_8 = createAttribute(builderFactory, "Hl7 Permissions",
                "urn:oasis:names:tc:xspa:1.0:subject:hl7:permission");
        Iterator itr = permissions.iterator();
        while (itr.hasNext()) {
            attrPID_8 = AddAttributeValue(builderFactory, attrPID_8, itr.next().toString(), "", "");
        }
        attrStmt.getAttributes().add(attrPID_8);

        assertion.getStatements().add(attrStmt);

    } catch (ConfigurationException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }

    return assertion;
}

From source file:com.github.markserrano.jsonquery.jpa.util.DateTimeUtil.java

License:Apache License

public static DateTime normalize(DateTime dateTime) {
    if (dateTime.toString().matches(".+(\\+)[0-9][0-9]:[0-9][0-9]")) {
        dateTime = dateTime.minusHours(dateTime.getHourOfDay());

    } else if (dateTime.toString().matches(".+(\\-)[0-9][0-9]:[0-9][0-9]")) {
        dateTime = dateTime.plusHours(24 - dateTime.getHourOfDay());
    }/* www  .  j av a 2s  .com*/
    return dateTime;
}

From source file:com.github.markserrano.jsonquery.jpa.util.DateTimeUtil.java

License:Apache License

public static Map<String, DateTime> getYesterdaySpan() {
    DateTime now = new DateTime();

    DateTime from = now.minusDays(1).minusHours(now.getHourOfDay()).minusMinutes(now.getMinuteOfHour())
            .minusSeconds(now.getSecondOfMinute()).minusMillis(now.getMillisOfSecond());

    DateTime to = from.plusHours(23).plusMinutes(59).plusSeconds(59);

    Map<String, DateTime> map = new HashMap<String, DateTime>();
    map.put("from", from);
    map.put("to", to);

    return map;//from w w  w. jav  a 2 s.  com
}

From source file:com.github.markserrano.jsonquery.jpa.util.DateTimeUtil.java

License:Apache License

public static String toDateRangeQuery(String filter, String datefield) {
    DateTime from = DateTimeUtil.getDateTime(filter, datefield);
    DateTime to = from.plusHours(23).plusMinutes(59).plusSeconds(59);

    // Replace operator from "eq" to "ge"
    filter = filter.replace("\"field\":\"" + datefield + "\",\"op\":\"eq\"",
            "\"field\":\"" + datefield + "\",\"op\":\"ge\"");
    filter = QueryUtil.addAnd(filter, datefield, OperatorEnum.LESSER_EQUAL, to.toString());

    return filter;
}