Example usage for org.joda.time DateTime minus

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

Introduction

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

Prototype

public DateTime minus(ReadablePeriod period) 

Source Link

Document

Returns a copy of this datetime with the specified period taken away.

Usage

From source file:org.jevis.commons.dataprocessing.Options.java

License:Open Source License

/**
 * Return sthe first period matching the period, offset and target date
 *
 * @param date target date to find the matching period
 * @param period period/*from w w w .j a va  2s  .  c  o m*/
 * @param offset start offset
 * @return
 */
public static DateTime findFirstDuration(DateTime date, Period period, DateTime offset) {
    //        System.out.println("findFirstDuration: " + date + "   p: " + period);
    DateTime startD = new DateTime();
    DateTime fistPeriod = offset;
    //        System.out.println("week: " + date.getWeekOfWeekyear());
    //        
    while (fistPeriod.isBefore(date) || fistPeriod.isEqual(date)) {
        fistPeriod = fistPeriod.plus(period);
    }
    fistPeriod = fistPeriod.minus(period);

    System.out.println("finding date in: " + ((new DateTime()).getMillis() - startD.getMillis()) + "ms");
    System.out.println("first offset date: offset:" + offset + "   for period: " + period + "   input date: "
            + date + "  fistPeriod: " + fistPeriod);
    return fistPeriod;
}

From source file:org.jevis.commons.dataprocessing.ProcessOptions.java

License:Open Source License

/**
 * Return sthe first period matching the period, offset and target date
 *
 * @param date target date to find the matching period
 * @param period period//from  w w  w.  ja v  a 2 s.co  m
 * @param offset start offset
 * @return
 */
public static DateTime findFirstDuration(DateTime date, Period period, DateTime offset) {
    //        System.out.println("findFirstDuration: " + date + "   p: " + period);
    DateTime startD = new DateTime();
    DateTime fistPeriod = offset;
    //        System.out.println("week: " + date.getWeekOfWeekyear());
    //
    while (fistPeriod.isBefore(date) || fistPeriod.isEqual(date)) {
        fistPeriod = fistPeriod.plus(period);
    }
    fistPeriod = fistPeriod.minus(period);

    System.out.println("finding date in: " + ((new DateTime()).getMillis() - startD.getMillis()) + "ms");
    System.out.println("first offset date: offset:" + offset + "   for period: " + period + "   input date: "
            + date + "  fistPeriod: " + fistPeriod);
    return fistPeriod;
}

From source file:org.jevis.jealarm.AlarmHandler.java

License:Open Source License

/**
 * Checks the Data Objects for alarms and send an email.
 *
 * @param alarm//from w w w.j  av a  2  s .co  m
 * @throws JEVisException
 */
public void checkAlarm(Alarm alarm) throws JEVisException {
    List<JEVisObject> outOfBount = new ArrayList<>();
    List<JEVisObject> dps = getDataPoints(alarm);

    DateTime now = new DateTime();
    DateTime ignoreTS = now.minus(Period.hours(alarm.getIgnoreOld()));
    DateTime limit = now.minus(Period.hours(alarm.getTimeLimit()));

    for (JEVisObject obj : dps) {
        JEVisSample lsample = obj.getAttribute("Value").getLatestSample();
        if (lsample != null) {
            if (lsample.getTimestamp().isBefore(limit) && lsample.getTimestamp().isAfter(ignoreTS)) {
                outOfBount.add(obj);
            }
        }
    }
    DateTimeFormatter dtf = DateTimeFormat.forPattern("yyyy-MM-dd HH:mm");
    StringBuilder sb = new StringBuilder();

    sb.append("<html>");
    sb.append(alarm.getGreeting());
    sb.append(",");
    sb.append("<br>");
    sb.append("<br>");
    sb.append(alarm.getMessage());
    sb.append("<br>");
    sb.append("<br>");

    String tabelCSS = "background-color:#FFF;" + "text-color: #024457;" + "outer-border: 1px solid #167F92;"
            + "empty-cells:show;" + "border-collapse:collapse;"
            //                + "border: 2px solid #D9E4E6;"
            + "cell-border: 1px solid #D9E4E6";

    String headerCSS = "background-color: #1a719c;" + "color: #FFF;";

    String rowCss = "text-color: #024457;padding: 5px;";//"border: 1px solid #D9E4E6;"

    String highlight = "background-color: #EAF3F3";

    sb.append("<table style=\"" + tabelCSS + "\" border=\"1\" >"); //border=\"0\"
    sb.append("<tr style=\"" + headerCSS + "\" >" + "    <th>Organisation</th>" + "    <th>Building</th>"
            + "    <th>Directory</th>" + "    <th>Datapoint</th>" + "    <th>Last Value</th>" + "  </tr>");

    JEVisClass orga = _ds.getJEVisClass("Organization");
    JEVisClass building = _ds.getJEVisClass("Monitored Object");
    JEVisClass dir = _ds.getJEVisClass("Data Directory");

    boolean odd = false;
    for (JEVisObject probelObj : outOfBount) {
        String css = rowCss;
        if (odd) {
            css += highlight;
        }
        odd = !odd;

        sb.append("<tr>");// style=\"border: 1px solid #D9E4E6;\">");

        sb.append("<td style=\"");
        sb.append(css);
        sb.append("\">");
        sb.append(getParentName(probelObj, orga));
        sb.append("</td>");

        sb.append("<td style=\"");
        sb.append(css);
        sb.append("\">");
        sb.append(getParentName(probelObj, building));
        sb.append("</td>");

        sb.append("<td style=\"");
        sb.append(css);
        sb.append("\">");
        sb.append(getParentName(probelObj, dir));
        sb.append("</td>");

        sb.append("<td style=\"");
        sb.append(css);
        sb.append("\">");
        sb.append(probelObj.getName());
        sb.append("</td>");

        //Last Sample
        //TODO: the fetch the sample again everytime is bad for the performace, store the sample somewhere
        sb.append("<td style=\"");
        sb.append(css);
        sb.append("\">");
        sb.append(dtf.print(probelObj.getAttribute("Value").getLatestSample().getTimestamp()));
        sb.append("</td>");

        sb.append("</tr>");
    }

    sb.append("</tr>");
    sb.append("</tr>");
    sb.append("</table>");
    sb.append("<br>");
    sb.append(_conf.getSmtpSignatur());
    sb.append("</html>");

    if (outOfBount.isEmpty() && alarm.isIgnoreFalse()) {
        //Do nothing then
    } else {
        sendAlarm(_conf, alarm, sb.toString());
    }

}

From source file:org.kalypso.ogc.sensor.filter.filters.interval.IntervalValuesOperation.java

License:Open Source License

private IntervalIndex buildSourceIndex() throws SensorException {
    final IntervalIndex index = new IntervalIndex();

    final IAxis[] axes = m_sourceModel.getAxes();
    final IAxis dateAxis = AxisUtils.findDateAxis(axes);

    final Period step = findStep();

    final DateTimeZone zone = DateTimeZone.forTimeZone(m_timeZone);

    for (int i = 0; i < m_sourceModel.size(); i++) {
        final Date date = (Date) m_sourceModel.get(i, dateAxis);

        final DateTime to = new DateTime(date, zone);
        final DateTime from = to.minus(step);
        final Interval sourceInterval = new Interval(from, to);

        final IntervalData sourceData = m_axes.asIntervalData(sourceInterval, m_sourceModel, i);
        index.insert(sourceData);// w ww. ja  v  a2  s .  com
    }

    return index;
}

From source file:org.kalypso.ui.rrm.internal.calccase.CatchmentModelHelper.java

License:Open Source License

/**
 * This function calculates the range for the timeseries to be generated. The range equals the range defined in the
 * simulation adjusted as follows://  ww w.ja v  a  2 s  . c o  m
 * <ul>
 * <li>1 timestep earlier</li>
 * <li>3 timesteps later</li>
 * </ul>
 *
 * @param control
 *          The na control.
 * @param timestep
 *          The timestep.
 * @param timestamp
 *          The timestamp in UTC.
 * @return The date range.
 */
public static DateRange getRange(final NAControl control, final Period timestep, final LocalTime timestamp) {
    final Date simulationStart = control.getSimulationStart();
    final Date simulationEnd = control.getSimulationEnd();

    final DateTime start = new DateTime(simulationStart);
    final DateTime end = new DateTime(simulationEnd);

    final DateTime adjustedStart = start.minus(timestep);
    final DateTime adjustedEnd = end.plus(timestep).plus(timestep).plus(timestep);

    if (timestep.getDays() == 0 || timestamp == null)
        return new DateRange(adjustedStart.toDate(), adjustedEnd.toDate());

    /* Convert to a date with the kalypso timezone. */
    /* The date fields are ignored. */
    final DateTime timestampUTC = timestamp
            .toDateTimeToday(DateTimeZone.forTimeZone(TimeZone.getTimeZone("UTC"))); //$NON-NLS-1$
    final DateTime timestampDate = new DateTime(timestampUTC.toDate(),
            DateTimeZone.forTimeZone(KalypsoCorePlugin.getDefault().getTimeZone()));

    /* Further adjust range by predefined time. */
    final DateTime startWithTime = adjustedStart.withTime(timestampDate.getHourOfDay(),
            timestampDate.getMinuteOfHour(), timestampDate.getSecondOfMinute(),
            timestampDate.getMillisOfSecond());
    final DateTime endWithTime = adjustedEnd.withTime(timestampDate.getHourOfDay(),
            timestampDate.getMinuteOfHour(), timestampDate.getSecondOfMinute(),
            timestampDate.getMillisOfSecond());

    /* New start must always be before unadjusted start, fix, if this is not the case. */
    DateTime startWithTimeFixed;
    if (startWithTime.isAfter(adjustedStart))
        startWithTimeFixed = startWithTime.minus(timestep);
    else
        startWithTimeFixed = startWithTime;

    /* New end must always be after unadjusted end, fix, if this is not the case. */
    DateTime endWithTimeFixed;
    if (endWithTime.isBefore(adjustedEnd))
        endWithTimeFixed = endWithTime.plus(timestep);
    else
        endWithTimeFixed = endWithTime;

    return new DateRange(startWithTimeFixed.toDate(), endWithTimeFixed.toDate());

}

From source file:org.kuali.kpme.tklm.time.timeblock.service.TimeBlockServiceImpl.java

License:Educational Community License

public List<TimeBlock> buildTimeBlocksSpanDates(Assignment assignment, String earnCode,
        TimesheetDocument timesheetDocument, DateTime beginDateTime, DateTime endDateTime, BigDecimal hours,
        BigDecimal amount, Boolean getClockLogCreated, Boolean getLunchDeleted, String spanningWeeks,
        String userPrincipalId) {
    DateTimeZone zone = HrServiceLocator.getTimezoneService().getUserTimezoneWithFallback();
    DateTime beginDt = beginDateTime.withZone(zone);
    DateTime endDt = beginDt.toLocalDate().toDateTime(endDateTime.withZone(zone).toLocalTime(), zone);
    if (endDt.isBefore(beginDt))
        endDt = endDt.plusDays(1);//w  w w. j a va  2s  .  c  om

    List<Interval> dayInt = TKUtils.getDaySpanForCalendarEntry(timesheetDocument.getCalendarEntry());
    TimeBlock firstTimeBlock = new TimeBlock();
    List<TimeBlock> lstTimeBlocks = new ArrayList<TimeBlock>();

    DateTime endOfFirstDay = null; // KPME-2568
    long diffInMillis = 0; // KPME-2568

    for (Interval dayIn : dayInt) {
        if (dayIn.contains(beginDt)) {
            if (dayIn.contains(endDt) || dayIn.getEnd().equals(endDt)) {
                // KPME-1446 if "Include weekends" check box is checked, don't add Sat and Sun to the timeblock list
                if (StringUtils.isEmpty(spanningWeeks)
                        && (dayIn.getStart().getDayOfWeek() == DateTimeConstants.SATURDAY
                                || dayIn.getStart().getDayOfWeek() == DateTimeConstants.SUNDAY)) {
                    // Get difference in millis for the next time block - KPME-2568
                    endOfFirstDay = endDt.withZone(zone);
                    diffInMillis = endOfFirstDay.minus(beginDt.getMillis()).getMillis();
                } else {
                    firstTimeBlock = createTimeBlock(timesheetDocument, beginDateTime, endDt, assignment,
                            earnCode, hours, amount, false, getLunchDeleted, userPrincipalId);
                    lstTimeBlocks.add(firstTimeBlock);
                }
            } else {
                //TODO move this to prerule validation
                //throw validation error if this case met error
            }
        }
    }

    DateTime endTime = endDateTime.withZone(zone);
    if (firstTimeBlock.getEndDateTime() != null) { // KPME-2568
        endOfFirstDay = firstTimeBlock.getEndDateTime().withZone(zone);
        diffInMillis = endOfFirstDay.minus(beginDt.getMillis()).getMillis();
    }
    DateTime currTime = beginDt.plusDays(1);
    while (currTime.isBefore(endTime) || currTime.isEqual(endTime)) {
        // KPME-1446 if "Include weekends" check box is checked, don't add Sat and Sun to the timeblock list
        if (StringUtils.isEmpty(spanningWeeks) && (currTime.getDayOfWeek() == DateTimeConstants.SATURDAY
                || currTime.getDayOfWeek() == DateTimeConstants.SUNDAY)) {
            // do nothing
        } else {
            TimeBlock tb = createTimeBlock(timesheetDocument, currTime, currTime.plus(diffInMillis), assignment,
                    earnCode, hours, amount, false, getLunchDeleted, userPrincipalId);
            lstTimeBlocks.add(tb);
        }
        currTime = currTime.plusDays(1);
    }
    return lstTimeBlocks;
}

From source file:org.mrgeo.geometry.splitter.TimeSpanGeometrySplitter.java

License:Apache License

@Override
public void initialize(Map<String, String> splitterProperties, final boolean uuidOutputNames,
        final String[] outputNames) {
    String timeFormat = splitterProperties.get(TIME_FORMAT_PROPERTY);
    if (timeFormat == null || timeFormat.isEmpty()) {
        dtf = ISODateTimeFormat.dateTime();
    } else {//w  w w  .j  a  v  a  2  s  .co m
        dtf = DateTimeFormat.forPattern(timeFormat);
    }
    DateTime startTime = getTimeProperty(splitterProperties, START_TIME_PROPERTY, dtf);
    DateTime endTime = getTimeProperty(splitterProperties, END_TIME_PROPERTY, dtf);
    String strInterval = splitterProperties.get(INTERVAL_PROPERTY);
    if (strInterval == null || strInterval.isEmpty()) {
        throw new IllegalArgumentException("Missing interval property for time span geometry splitter");
    }
    int seconds = -1;
    try {
        seconds = Integer.parseInt(strInterval);
    } catch (NumberFormatException nfe) {
        throw new IllegalArgumentException(
                "Invalid value for interval property for time span geometry splitter");
    }
    Period interval = Period.seconds(seconds);
    startField = splitterProperties.get(START_FIELD_PROPERTY);
    if (startField == null || startField.isEmpty()) {
        throw new IllegalArgumentException("Missing startField property for time span geometry splitter");
    }
    endField = splitterProperties.get(END_FIELD_PROPERTY);
    if (endField == null || endField.isEmpty()) {
        throw new IllegalArgumentException("Missing endField property for time span geometry splitter");
    }
    compareType = TimeSpanGeometrySplitter.CompareType.END_TIME;
    String strCompareType = splitterProperties.get(COMPARE_TYPE_PROPERTY);
    if (strCompareType != null && !strCompareType.isEmpty()) {
        compareType = compareTypeFromString(strCompareType);
    }

    List<DateTime> breakpointsList = new ArrayList<DateTime>();
    DateTime currBreakpoint = startTime;
    while (currBreakpoint.compareTo(endTime) <= 0) {
        breakpointsList.add(currBreakpoint);
        currBreakpoint = currBreakpoint.plus(interval);
    }
    // If the endTime is greater than the last breakpoint, then
    // include one more breakpoint.
    if (endTime.compareTo(currBreakpoint.minus(interval)) > 0) {
        breakpointsList.add(currBreakpoint);
    }
    if ((outputNames != null) && (breakpointsList.size() != outputNames.length)) {
        throw new IllegalArgumentException(
                "Invalid set of output names specified for the time span" + " geometry splitter. There are "
                        + breakpointsList.size() + " breakpoints, and " + outputNames.length + " output names");
    }
    breakpoints = new DateTime[breakpointsList.size()];
    breakpointsList.toArray(breakpoints);
    outputs = new String[breakpoints.length];
    for (int i = 0; i < breakpoints.length; i++) {
        String output;
        if (outputNames != null) {
            output = outputNames[i];
        } else {
            if (uuidOutputNames) {
                output = UUID.randomUUID().toString();
            } else {
                output = breakpoints[i].toString(dtf);
                // DirectoryMultipleOutputs only allows alphanumeric characters
                output = output.replaceAll("[^\\p{Alnum}]", "");
            }
        }
        outputs[i] = output;
    }
}

From source file:org.mythtv.android.utils.DateUtils.java

License:Open Source License

public static DateTime getPreviousDay(DateTime day) {

    day = day.minus(Period.days(1));

    return getEndOfDay(day);
}

From source file:org.n52.sos.ds.pgsql.PGSQLDescribeSensorDAO.java

License:Open Source License

/**
 * creates and returns the where clause for time period parameter
 * /*from ww w  .j av a  2 s .c o  m*/
 * @param timePeriod
 *        TimePeriod object for which the where clause should be created
 * @param operator
 *        name of timeObs element (e.g. ogc:after or ogc:TEquals)
 * @return String containing the where clause for time period parameter
 * @throws ParseException
 *         if parsing begin or end date failed
 * @throws OwsExceptionReport
 *         if one parameter is incorrect or a required paramter is missing
 */
private String createWhereClause4timePeriod(TimePeriod timePeriod, TimeOperator operator, String procedure_id)
        throws OwsExceptionReport {

    DateTime start = timePeriod.getStart();
    String indetStartTime = timePeriod.getStartIndet();
    DateTime end = timePeriod.getEnd();
    String indetEndTime = timePeriod.getEndIndet();
    Period duration = timePeriod.getDuration();

    String result = "";

    switch (operator) {

    // before
    case TM_Before:
        // //if indetPosition of endPosition = After throw exception!
        if (indetEndTime != null) {
            if (indetEndTime.equals(GMLConstants.IndetTimeValues.after.name())) {
                OwsExceptionReport se = new OwsExceptionReport();
                se.addCodedException(OwsExceptionReport.ExceptionCode.InvalidParameterValue,
                        DescribeSensorParams.time.toString(),
                        "The value of indeterminatePosition = '" + indetEndTime
                                + "'  of EndPosition in TimePeriod"
                                + " is in conflict with the temporal operator of time = '" + operator);
                throw se;
            }
        }

        result += " AND (" + PGDAOConstants.procHistTn + "." + PGDAOConstants.procHistTimeStampCn + " < " + "'"
                + SosDateTimeUtilities.formatDateTime2IsoString(end) + "'" + ")";
        break; // end before

    // after
    case TM_After:
        // if indetPosition of beginPosition = Before throw exception!
        if (indetEndTime != null) {
            if (indetEndTime.equals(GMLConstants.IndetTimeValues.before.name())) {
                OwsExceptionReport se = new OwsExceptionReport();
                se.addCodedException(OwsExceptionReport.ExceptionCode.InvalidParameterValue,
                        DescribeSensorParams.time.toString(),
                        "The value of indeterminatePosition = '" + indetStartTime
                                + "'  of StartPosition in TimePeriod"
                                + " is in conflict with the temporal operator of time = '" + operator);
                throw se;
            }
        }

        result += " AND (" + PGDAOConstants.procHistTn + "." + PGDAOConstants.procHistTimeStampCn + " > " + "'"
                + SosDateTimeUtilities.formatDateTime2IsoString(start) + "'" + ")";
        break; // end after

    // during
    case TM_During:

        /*
         * if duration not null, values between a duration should be returned. Only the endPosition
         * PGConfigurator.timestampCn or indeterminateTime of endPosition is read in. The begin Position
         * is not received attention. A timePeriod element which works may look like: 
         * <ogc:During>
         * <gml:TimePeriod> 
         * <gml:beginPosition indeterminatePosition="unknown"></gml:beginPosition>
         * <gml:endPosition indeterminatePosition="now">2005-10-05T10:17:00</gml:endPosition>
         * <gml:duration>P5M</gml:duration>
         * </gml:TimePeriod> 
         * </ogc:During>
         */
        if (duration != null) {

            if (indetEndTime != null && indetEndTime.equals(GMLConstants.IndetTimeValues.now.name())) {
                end = new DateTime();
            }

            else if (end == null) {
                OwsExceptionReport se = new OwsExceptionReport();
                se.addCodedException(OwsExceptionReport.ExceptionCode.InvalidParameterValue,
                        DescribeSensorParams.time.toString(),
                        "If duration is set, either timePosition of endPosition in timePeriod"
                                + " must be set or indeterminatePosition of endPosition must be 'now' or 'unknown', where"
                                + "'unknown' accords to 'now'.");
                throw se;
            }
            DateTime begin = end.minus(duration);

            result += " AND (" + PGDAOConstants.procHistTn + "." + PGDAOConstants.procHistTimeStampCn + " > "
                    + "'" + SosDateTimeUtilities.formatDateTime2IsoString(begin) + "'" + " AND "
                    + PGDAOConstants.procHistTn + "." + PGDAOConstants.procHistTimeStampCn + " < " + "'"
                    + SosDateTimeUtilities.formatDateTime2IsoString(end) + "'" + ")";

        }

        else {
            if ((indetStartTime != null && indetStartTime.equals(GMLConstants.IndetTimeValues.before.name()))
                    && (indetEndTime != null
                            && indetEndTime.equals(GMLConstants.IndetTimeValues.after.name()))) {
                OwsExceptionReport se = new OwsExceptionReport();
                se.addCodedException(OwsExceptionReport.ExceptionCode.InvalidParameterValue,
                        DescribeSensorParams.time.toString(),
                        "The value of indeterminatePosition of StartPosition ='" + indetStartTime
                                + "'  and of indeterminatePosition of EndPosition ='" + indetEndTime
                                + "' in TimePeriod" + " is in conflict with the temporal operator of time = '"
                                + operator);
                throw se;
            }

            result += " AND (" + PGDAOConstants.procHistTn + "." + PGDAOConstants.procHistTimeStampCn + " > "
                    + "'" + SosDateTimeUtilities.formatDateTime2IsoString(start) + "'" + " AND "
                    + PGDAOConstants.procHistTn + "." + PGDAOConstants.procHistTimeStampCn + " < " + "'"
                    + SosDateTimeUtilities.formatDateTime2IsoString(end) + "'" + ")";

        }
        break; // end during

    // after
    case TM_Equals:

        if (indetStartTime != null && indetEndTime != null
                && indetStartTime.equals(FilterConstants.TimeOperator.TM_Before)
                && indetEndTime.equals(FilterConstants.TimeOperator.TM_After)) {
            OwsExceptionReport se = new OwsExceptionReport();
            se.addCodedException(OwsExceptionReport.ExceptionCode.InvalidParameterValue,
                    DescribeSensorParams.time.toString(),
                    "The value of indeterminatePosition of StartPosition ='" + indetStartTime
                            + "'  and of indeterminatePosition of EndPosition ='" + indetEndTime
                            + "' in TimePeriod" + " is in conflict with the temporal operator of time = '"
                            + operator);
            throw se;
        }
        result += " AND (" + PGDAOConstants.procHistTn + "." + PGDAOConstants.procHistTimeStampCn + " >= " + "'"
                + SosDateTimeUtilities.formatDateTime2IsoString(start) + "'" + "AND "
                + PGDAOConstants.procHistTn + "." + PGDAOConstants.procHistTimeStampCn + " <= " + "'"
                + SosDateTimeUtilities.formatDateTime2IsoString(end) + "'" + ")";
        break; // end after
    }

    return result.toString();
}

From source file:org.n52.sos.ds.pgsql.PGSQLGetObservationDAO.java

License:Open Source License

/**
 * creates and returns the where clause for time period parameter
 * //from ww w  . j  a  va  2 s . c o  m
 * @param timePeriod
 *        TimePeriod object for which the where clause should be created
 * @param operator
 *        name of timeObs element (e.g. ogc:after or ogc:TEquals)
 * @param offeringID
 *        tableName of the PGConfigurator.obsTn
 * @return String containing the where clause for time period parameter
 * @throws ParseException
 *         if parsing begin or end DateTime failed
 * @throws OwsExceptionReport
 *         if one parameter is incorrect or a required paramter is missing
 */
private String getWhereClause4timePeriod(TimePeriod timePeriod, TimeOperator operator)
        throws OwsExceptionReport {

    DateTime start = timePeriod.getStart();
    String indetStartTime = timePeriod.getStartIndet();
    DateTime end = timePeriod.getEnd();
    String indetEndTime = timePeriod.getEndIndet();
    Period duration = timePeriod.getDuration();

    // setting start to now if indetStartTime is "now"
    if (indetStartTime != null && indetStartTime.equalsIgnoreCase(GMLConstants.IndetTimeValues.now.name())) {
        start = now;
    }
    // setting end to now if indetEndTime is "now"
    if (indetEndTime != null && indetEndTime.equalsIgnoreCase(GMLConstants.IndetTimeValues.now.name())) {
        end = now;
    }
    // setting end to max tst in database
    if (indetEndTime != null && indetEndTime.equals(GMLConstants.IndetTimeValues.unknown.name())) {
        end = SosConfigurator.getInstance().getFactory().getConfigDAO().getMaxDate4Observations().plusMillis(1);
    }
    // setting start to min tst in database
    if (indetStartTime != null && indetStartTime.equals(GMLConstants.IndetTimeValues.unknown.name())) {
        start = SosConfigurator.getInstance().getFactory().getConfigDAO().getMinDate4Observations()
                .minusMillis(1);
    }

    // is tst specified for 'after' or 'before' in beginPosition
    if (indetStartTime != null && (indetStartTime.equals(GMLConstants.IndetTimeValues.after.name())
            || indetStartTime.equals(GMLConstants.IndetTimeValues.before.name())) && start == null) {
        OwsExceptionReport se = new OwsExceptionReport();
        se.addCodedException(OwsExceptionReport.ExceptionCode.InvalidParameterValue,
                GetObservationParams.eventTime.toString(),
                "The value of indeterminatePosition = '" + indetStartTime + "' of beginPosition in TimePeriod"
                        + " requires a specified timestamp");
        throw se;
    }

    // is tst specified for 'after' or 'before' in endPosition
    if (indetEndTime != null && (indetEndTime.equals(GMLConstants.IndetTimeValues.after.name())
            || indetEndTime.equals(GMLConstants.IndetTimeValues.before.name())) && end == null) {
        OwsExceptionReport se = new OwsExceptionReport();
        se.addCodedException(OwsExceptionReport.ExceptionCode.InvalidParameterValue,
                GetObservationParams.eventTime.toString(), "The value of indeterminatePosition = '"
                        + indetEndTime + "' of endPosition in TimePeriod" + " requires a specified timestamp");
        throw se;
    }

    StringBuilder result = new StringBuilder();

    switch (operator) {

    // before
    case TM_Before:
        // //if indetPosition of endPosition = After throw exception!
        if (indetEndTime != null) {
            if (indetEndTime.equals(GMLConstants.IndetTimeValues.after.name())) {
                OwsExceptionReport se = new OwsExceptionReport();
                se.addCodedException(OwsExceptionReport.ExceptionCode.InvalidParameterValue,
                        GetObservationParams.eventTime.toString(),
                        "The value of indeterminatePosition = '" + indetEndTime
                                + "'  of EndPosition in TimePeriod"
                                + " is in conflict with the temporal operator of eventTime = '" + operator);
                throw se;
            }
        }
        result.append(" (" + PGDAOConstants.obsTn + "." + PGDAOConstants.timestampCn + " < " + "'"
                + SosDateTimeUtilities.formatDateTime2IsoString(end) + "'" + ")");
        break; // end before

    // after
    case TM_After:
        // if indetPosition of beginPosition = Before throw exception!
        if (indetStartTime != null) {
            if (indetStartTime.equals(GMLConstants.IndetTimeValues.before.name())) {
                OwsExceptionReport se = new OwsExceptionReport();
                se.addCodedException(OwsExceptionReport.ExceptionCode.InvalidParameterValue,
                        GetObservationParams.eventTime.toString(),
                        "The value of indeterminatePosition = '" + indetStartTime
                                + "'  of StartPosition in TimePeriod"
                                + " is in conflict with the temporal operator of eventTime = '" + operator);
                throw se;
            }
        }
        result.append(" (" + PGDAOConstants.obsTn + "." + PGDAOConstants.timestampCn + " > " + "'"
                + SosDateTimeUtilities.formatDateTime2IsoString(start) + "'" + ")");
        break; // end after

    // during
    case TM_During:

        /*
         * if duration not null, values between a duration should be returned. Only the endPosition
         * PGConfigurator.timestampCn or indeterminateTime of endPosition is read in. The begin Position
         * is not received attention. A timePeriod element which works may look like: <ogc:During>
         * <gml:TimePeriod> <gml:beginPosition indeterminatePosition="unknown"></gml:beginPosition>
         * <gml:endPosition indeterminatePosition="now">2005-10-05T10:17:00</gml:endPosition>
         * <gml:duration>P5M</gml:duration> </gml:TimePeriod> </ogc:During>
         */
        if (duration != null) {

            if (indetEndTime != null && (indetEndTime.equals(GMLConstants.IndetTimeValues.now.name())
                    || indetEndTime.equals(GMLConstants.IndetTimeValues.unknown.name()))) {
                end = now;
            } else if (indetEndTime != null && (indetEndTime.equals(GMLConstants.IndetTimeValues.after.name()))
                    || indetEndTime.equals(GMLConstants.IndetTimeValues.before.name())) {
                OwsExceptionReport se = new OwsExceptionReport();
                se.addCodedException(OwsExceptionReport.ExceptionCode.InvalidParameterValue,
                        GetObservationParams.eventTime.toString(),
                        "If duration is set indeterminatePositions 'after' and 'before' are not allowed.");
                throw se;
            }

            else if (end == null) {
                OwsExceptionReport se = new OwsExceptionReport();
                se.addCodedException(OwsExceptionReport.ExceptionCode.InvalidParameterValue,
                        GetObservationParams.eventTime.toString(),
                        "If duration is set, either timePosition of endPosition in timePeriod"
                                + " must be set or indeterminatePosition of endPosition must be 'now' or 'unknown', where"
                                + "'unknown' accords to 'now'.");
                throw se;
            }
            DateTime begin = end.minus(duration);

            result.append(" (" + PGDAOConstants.obsTn + "." + PGDAOConstants.timestampCn + " > " + "'"
                    + SosDateTimeUtilities.formatDateTime2IsoString(begin) + "'" + " AND "
                    + PGDAOConstants.obsTn + "." + PGDAOConstants.timestampCn + " < " + "'"
                    + SosDateTimeUtilities.formatDateTime2IsoString(end) + "'" + ")");

        }

        else {
            if (indetStartTime != null && indetStartTime.equals(GMLConstants.IndetTimeValues.before.name())) {
                OwsExceptionReport se = new OwsExceptionReport();
                se.addCodedException(OwsExceptionReport.ExceptionCode.InvalidParameterValue,
                        GetObservationParams.eventTime.toString(),
                        "The value of indeterminatePosition of StartPosition ='" + indetStartTime
                                + "' in TimePeriod"
                                + " is in conflict with the temporal operator of eventTime = '" + operator);
                throw se;
            } else if (indetEndTime != null && indetEndTime.equals(GMLConstants.IndetTimeValues.after.name())) {
                OwsExceptionReport se = new OwsExceptionReport();
                se.addCodedException(OwsExceptionReport.ExceptionCode.InvalidParameterValue,
                        GetObservationParams.eventTime.toString(),
                        "The value of indeterminatePosition of EndPosition ='" + indetEndTime
                                + "' in TimePeriod"
                                + " is in conflict with the temporal operator of eventTime = '" + operator);
                throw se;
            }

            result.append(" (" + PGDAOConstants.obsTn + "." + PGDAOConstants.timestampCn + " > " + "'"
                    + SosDateTimeUtilities.formatDateTime2IsoString(start) + "'" + " AND "
                    + PGDAOConstants.obsTn + "." + PGDAOConstants.timestampCn + " < " + "'"
                    + SosDateTimeUtilities.formatDateTime2IsoString(end) + "'" + ")");

        }
        break; // end during

    // after
    case TM_Equals:

        if (indetStartTime != null && indetStartTime.equals(GMLConstants.IndetTimeValues.before.name())) {
            OwsExceptionReport se = new OwsExceptionReport();
            se.addCodedException(OwsExceptionReport.ExceptionCode.InvalidParameterValue,
                    GetObservationParams.eventTime.toString(),
                    "The value of indeterminatePosition of StartPosition ='" + indetStartTime
                            + "' in TimePeriod" + " is in conflict with the temporal operator of eventTime = '"
                            + operator);
            throw se;
        } else if (indetEndTime != null && indetEndTime.equals(GMLConstants.IndetTimeValues.after.name())) {
            OwsExceptionReport se = new OwsExceptionReport();
            se.addCodedException(OwsExceptionReport.ExceptionCode.InvalidParameterValue,
                    GetObservationParams.eventTime.toString(),
                    "The value of indeterminatePosition of EndPosition ='" + indetEndTime + "' in TimePeriod"
                            + " is in conflict with the temporal operator of eventTime = '" + operator);
            throw se;
        }

        result.append(" (" + PGDAOConstants.obsTn + "." + PGDAOConstants.timestampCn + " >= " + "'"
                + SosDateTimeUtilities.formatDateTime2IsoString(start) + "'" + "AND " + PGDAOConstants.obsTn
                + "." + PGDAOConstants.timestampCn + " <= " + "'"
                + SosDateTimeUtilities.formatDateTime2IsoString(end) + "'" + ")");
        break; // end after
    }

    return result.toString();
}