Example usage for org.joda.time DateTime getHourOfDay

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

Introduction

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

Prototype

public int getHourOfDay() 

Source Link

Document

Get the hour of day field value.

Usage

From source file:org.onebusaway.admin.util.VehicleStatusBuilder.java

License:Apache License

private String extractTime(String date) {
    DateTimeFormatter formatter = ISODateTimeFormat.dateTimeNoMillis();
    DateTime dateTime = formatter.parseDateTime(date);
    int hour = dateTime.getHourOfDay();
    String formattedHour = String.format("%02d", hour);
    int minute = dateTime.getMinuteOfHour();
    String formattedMinute = String.format("%02d", minute);
    return formattedHour + ":" + formattedMinute;
}

From source file:org.opencastproject.index.service.catalog.adapter.DublinCoreMetadataUtil.java

License:Educational Community License

/**
 * Gets the current hour, minute and second from a dublin core period if available.
 *
 * @param period//from   w w w  .j ava  2 s. co m
 *          The current period from dublin core.
 * @return A new DateTime with the current hour, minute and second.
 */
static DateTime getCurrentStartTime(Opt<DCMIPeriod> period) {
    DateTime currentStartTime = new DateTime();
    currentStartTime = currentStartTime.withZone(DateTimeZone.UTC);
    currentStartTime = currentStartTime.withHourOfDay(0);
    currentStartTime = currentStartTime.withMinuteOfHour(0);
    currentStartTime = currentStartTime.withSecondOfMinute(0);

    if (period.isSome() && period.get().hasStart()) {
        DateTime fromDC = new DateTime(period.get().getStart().getTime());
        fromDC = fromDC.withZone(DateTimeZone.UTC);
        currentStartTime = currentStartTime.withZone(DateTimeZone.UTC);
        currentStartTime = currentStartTime.withHourOfDay(fromDC.getHourOfDay());
        currentStartTime = currentStartTime.withMinuteOfHour(fromDC.getMinuteOfHour());
        currentStartTime = currentStartTime.withSecondOfMinute(fromDC.getSecondOfMinute());
    }
    return currentStartTime;
}

From source file:org.opencastproject.index.service.catalog.adapter.DublinCoreMetadataUtil.java

License:Educational Community License

/**
 * Sets the start date in a dublin core catalog to the right value and keeps the start time and duration the same.
 *
 * @param dc//from   w w w.  j a va  2  s .  c  o m
 *          The dublin core catalog to adjust
 * @param field
 *          The metadata field that contains the start date.
 * @param ename
 *          The EName in the catalog to identify the property that has the dublin core period.
 */
static void setTemporalStartDate(DublinCoreCatalog dc, MetadataField<?> field, EName ename) {
    if (field.getValue().isNone() || (field.getValue().get() instanceof String
            && StringUtils.isBlank(field.getValue().get().toString()))) {
        logger.debug("No value was set for metadata field with dublin core id '{}' and json id '{}'",
                field.getInputID(), field.getOutputID());
        return;
    }
    try {
        // Get the current date
        SimpleDateFormat dateFormat = MetadataField.getSimpleDateFormatter(field.getPattern().get());
        Date startDate = dateFormat.parse((String) field.getValue().get());
        // Get the current period
        Opt<DCMIPeriod> period = getPeriodFromCatalog(dc, ename);
        // Get the current duration
        Long duration = getDuration(period);
        // Get the current start time hours, minutes and seconds
        DateTime currentStartTime = getCurrentStartTime(period);
        // Setup the new start time
        DateTime startDateTime = new DateTime(startDate.getTime());
        startDateTime = startDateTime.withZone(DateTimeZone.UTC);
        startDateTime = startDateTime.withHourOfDay(currentStartTime.getHourOfDay());
        startDateTime = startDateTime.withMinuteOfHour(currentStartTime.getMinuteOfHour());
        startDateTime = startDateTime.withSecondOfMinute(currentStartTime.getSecondOfMinute());
        // Get the current end date based on new date and duration.
        DateTime endDate = new DateTime(startDateTime.toDate().getTime() + duration);
        dc.set(ename, EncodingSchemeUtils.encodePeriod(new DCMIPeriod(startDateTime.toDate(), endDate.toDate()),
                Precision.Second));
    } catch (ParseException e) {
        logger.error("Not able to parse date {} to update the dublin core because: {}", field.getValue(),
                ExceptionUtils.getStackTrace(e));
    }
}

From source file:org.opencastproject.index.service.catalog.adapter.DublinCoreMetadataUtil.java

License:Educational Community License

/**
 * Gets the current hour, minute and second from a dublin core period if available.
 *
 * @param period/*  w ww  . java 2s.co  m*/
 *          The current period from dublin core.
 * @return A new DateTime with the current hour, minute and second.
 */
private static DateTime getCurrentStartDateTime(Opt<DCMIPeriod> period) {
    DateTime currentStartTime = new DateTime();
    currentStartTime = currentStartTime.withZone(DateTimeZone.UTC);
    currentStartTime = currentStartTime.withYear(2001);
    currentStartTime = currentStartTime.withMonthOfYear(1);
    currentStartTime = currentStartTime.withDayOfMonth(1);
    currentStartTime = currentStartTime.withHourOfDay(0);
    currentStartTime = currentStartTime.withMinuteOfHour(0);
    currentStartTime = currentStartTime.withSecondOfMinute(0);

    if (period.isSome() && period.get().hasStart()) {
        DateTime fromDC = new DateTime(period.get().getStart().getTime());
        fromDC = fromDC.withZone(DateTimeZone.UTC);
        currentStartTime = currentStartTime.withZone(DateTimeZone.UTC);
        currentStartTime = currentStartTime.withYear(fromDC.getYear());
        currentStartTime = currentStartTime.withMonthOfYear(fromDC.getMonthOfYear());
        currentStartTime = currentStartTime.withDayOfMonth(fromDC.getDayOfMonth());
        currentStartTime = currentStartTime.withHourOfDay(fromDC.getHourOfDay());
        currentStartTime = currentStartTime.withMinuteOfHour(fromDC.getMinuteOfHour());
        currentStartTime = currentStartTime.withSecondOfMinute(fromDC.getSecondOfMinute());
    }
    return currentStartTime;
}

From source file:org.openehr.rm.datatypes.quantity.datetime.DvDateTimeParser.java

License:LGPL

public static DateTime defaultTime() {
    DateTime time = new DateTime();
    return new DateTime(1970, 1, 1, time.getHourOfDay(), time.getMinuteOfHour(), time.getSecondOfMinute(),
            time.getMillisOfSecond());//from w  w  w . j  a  va2s.  com
}

From source file:org.openehr.rm.datatypes.quantity.datetime.DvTime.java

License:LGPL

/**
 * Parses a string value and return a DvTime
 *///from w w w .  j a  v  a 2  s.  c o m
public DvTime parse(String value) {
    DateTime time = DvDateTimeParser.parseTime(value);
    return new DvTime(time.getHourOfDay(), time.getMinuteOfHour(), time.getSecondOfMinute(),
            time.getMillisOfSecond(), time.getZone().toTimeZone());
}

From source file:org.openhab.binding.stiebelheatpump.internal.CommunicationService.java

License:Open Source License

/**
 * This method set the time of the heat pump to the current time
 * /*w  w  w.java 2  s.c om*/
 * @return true if time has been updated
 */
public Map<String, String> setTime() throws StiebelHeatPumpException {

    startCommunication();
    Map<String, String> data = new HashMap<String, String>();

    Request timeRequest = null;

    for (Request request : heatPumpSettingConfiguration) {
        if (request.getName().equals("Time")) {
            timeRequest = request;
            break;
        }
    }

    if (timeRequest == null) {
        logger.warn("Could not find request definition for time settings! Skip setting time.");
        return data;
    }

    logger.debug("Loading current time data ...");
    try {
        // get time from heat pump
        byte[] requestMessage = createRequestMessage(timeRequest);
        byte[] response = getData(requestMessage);

        // get current time from local machine
        DateTime dt = DateTime.now();
        logger.debug("Current time is : {}", dt.toString());
        String weekday = Integer.toString(dt.getDayOfWeek() - 1);
        String day = Integer.toString(dt.getDayOfMonth());
        String month = Integer.toString(dt.getMonthOfYear());
        String year = Integer.toString(dt.getYearOfCentury());
        String seconds = Integer.toString(dt.getSecondOfMinute());
        String hours = Integer.toString(dt.getHourOfDay());
        String minutes = Integer.toString(dt.getMinuteOfHour());

        data = parser.parseRecords(response, timeRequest);

        boolean updateRequired = false;
        for (Map.Entry<String, String> entry : data.entrySet()) {
            String entryName = entry.getKey();
            String entryValue = entry.getValue();
            RecordDefinition currentRecord = null;

            for (RecordDefinition record : timeRequest.getRecordDefinitions()) {
                if (record.getName().equals(entryName)) {
                    currentRecord = record;
                    break;
                }
            }
            if (entryName.equals("WeekDay") && !entryValue.equals(weekday)) {
                updateRequired = true;
                response = parser.composeRecord(weekday, response, currentRecord);
                logger.debug("WeekDay needs update from {} to {}", entryValue, weekday);
                continue;
            }
            if (entryName.equals("Hours") && !entryValue.equals(hours)) {
                updateRequired = true;
                response = parser.composeRecord(hours, response, currentRecord);
                logger.debug("Hours needs update from {} to {}", entryValue, hours);
                continue;
            }
            if (entryName.equals("Minutes") && !entryValue.equals(minutes)) {
                updateRequired = true;
                response = parser.composeRecord(minutes, response, currentRecord);
                logger.debug("Minutes needs update from {} to {}", entryValue, minutes);
                continue;
            }
            if (entryName.equals("Seconds") && !entryValue.equals(seconds)) {
                updateRequired = true;
                response = parser.composeRecord(seconds, response, currentRecord);
                logger.debug("Seconds needs update from {} to {}", entryValue, seconds);
                continue;
            }
            if (entryName.equals("Year") && !entryValue.equals(year)) {
                updateRequired = true;
                response = parser.composeRecord(year, response, currentRecord);
                logger.debug("Year needs update from {} to {}", entryValue, year);
                continue;
            }
            if (entryName.equals("Month") && !entryValue.equals(month)) {
                updateRequired = true;
                response = parser.composeRecord(month, response, currentRecord);
                logger.debug("Month needs update from {} to {}", entryValue, month);
                continue;
            }
            if (entryName.equals("Day") && !entryValue.equals(day)) {
                updateRequired = true;
                response = parser.composeRecord(day, response, currentRecord);
                logger.debug("Day needs update from {} to {}", entryValue, day);
                continue;
            }
        }

        if (updateRequired) {
            Thread.sleep(WAITING_TIME_BETWEEN_REQUESTS);
            logger.info("Time need update. Set time to " + dt.toString());
            setData(response);

            Thread.sleep(WAITING_TIME_BETWEEN_REQUESTS);
            response = getData(requestMessage);
            data = parser.parseRecords(response, timeRequest);
            dt = DateTime.now();
            logger.debug("Current time is : {}", dt.toString());

        }
        return data;

    } catch (InterruptedException e) {
        throw new StiebelHeatPumpException(e.toString());
    }
}

From source file:org.opensmartgridplatform.adapter.protocol.dlms.domain.commands.DlmsHelperService.java

License:Open Source License

/**
 * Creates a COSEM date-time object based on the given {@code dateTime}.
 * <p>//  w  w w.j  a v  a  2 s .c  om
 * The deviation and clock status (is daylight saving active or not) are
 * based on the zone of the given {@code dateTime}.
 * <p>
 * To use a DateTime as indication of the instant of time to be used with a
 * specific deviation (that does not have to match the zone of the
 * DateTime), use {@link #asDataObject(DateTime, int, boolean)} instead.
 *
 * @param dateTime
 *            a DateTime to translate into COSEM date-time format.
 * @return a DataObject having a CosemDateTime matching the given DateTime
 *         as value.
 */
public DataObject asDataObject(final DateTime dateTime) {

    final CosemDate cosemDate = new CosemDate(dateTime.getYear(), dateTime.getMonthOfYear(),
            dateTime.getDayOfMonth());
    final CosemTime cosemTime = new CosemTime(dateTime.getHourOfDay(), dateTime.getMinuteOfHour(),
            dateTime.getSecondOfMinute(), dateTime.getMillisOfSecond() / 10);
    final int deviation = -(dateTime.getZone().getOffset(dateTime.getMillis()) / MILLISECONDS_PER_MINUTE);
    final ClockStatus[] clockStatusBits;
    if (dateTime.getZone().isStandardOffset(dateTime.getMillis())) {
        clockStatusBits = new ClockStatus[0];
    } else {
        clockStatusBits = new ClockStatus[1];
        clockStatusBits[0] = ClockStatus.DAYLIGHT_SAVING_ACTIVE;
    }
    final CosemDateTime cosemDateTime = new CosemDateTime(cosemDate, cosemTime, deviation, clockStatusBits);
    return DataObject.newDateTimeData(cosemDateTime);
}

From source file:org.opensmartgridplatform.adapter.protocol.dlms.domain.commands.DlmsHelperService.java

License:Open Source License

/**
 * Creates a COSEM date-time object based on the given {@code dateTime}.
 * This COSEM date-time will be for the same instant in time as the given
 * {@code dateTime} but may be for another time zone.
 * <p>/* w ww  . ja  v a  2  s  .c  o  m*/
 * Because the time zone with the {@code deviation} may be different than
 * the one with the {@code dateTime}, and the {@code deviation} alone does
 * not provide sufficient information on whether daylight savings is active
 * for the given instant in time, {@code dst} has to be provided to indicate
 * whether daylight savings are active.
 * <p>
 * If a DateTime for an instant in time is known with the correct time zone
 * set, you can use {@link #asDataObject(DateTime)} as a simpler
 * alternative.
 *
 * @param dateTime
 *            a DateTime indicating an instant in time to be used for the
 *            COSEM date-time.
 * @param deviation
 *            the deviation in minutes of local time to GMT to be included
 *            in the COSEM date-time.
 * @param dst
 *            {@code true} if daylight savings are active for the instant of
 *            the COSEM date-time, otherwise {@code false}.
 * @return a DataObject having a CosemDateTime for the instant of the given
 *         DateTime, with the given deviation and DST status information, as
 *         value.
 */
public DataObject asDataObject(final DateTime dateTime, final int deviation, final boolean dst) {
    /*
     * Create a date time that may not point to the right instant in time,
     * but that will give proper values getting the different fields for the
     * COSEM date and time objects.
     */
    final DateTime dateTimeWithOffset = dateTime.toDateTime(DateTimeZone.UTC).minusMinutes(deviation);
    final CosemDate cosemDate = new CosemDate(dateTimeWithOffset.getYear(), dateTimeWithOffset.getMonthOfYear(),
            dateTimeWithOffset.getDayOfMonth());
    final CosemTime cosemTime = new CosemTime(dateTimeWithOffset.getHourOfDay(),
            dateTimeWithOffset.getMinuteOfHour(), dateTimeWithOffset.getSecondOfMinute(),
            dateTimeWithOffset.getMillisOfSecond() / 10);
    final ClockStatus[] clockStatusBits;

    if (dst) {
        clockStatusBits = new ClockStatus[1];
        clockStatusBits[0] = ClockStatus.DAYLIGHT_SAVING_ACTIVE;
    } else {
        clockStatusBits = new ClockStatus[0];
    }
    final CosemDateTime cosemDateTime = new CosemDateTime(cosemDate, cosemTime, deviation, clockStatusBits);
    return DataObject.newDateTimeData(cosemDateTime);
}

From source file:org.openvpms.web.workspace.workflow.appointment.AbstractMultiDayScheduleGrid.java

License:Open Source License

/**
 * Returns the no. of slots an event occupies, from the specified slot.
 * <p>/*from   ww w . ja  v a2s. co  m*/
 * If the event begins prior to the slot, the remaining slots will be returned.
 *
 * @param event the event
 * @param slot  the starting slot
 * @return the no. of slots that the event occupies
 */
public int getSlots(PropertySet event, int slot) {
    DateTime endTime = new DateTime(event.getDate(ScheduleEvent.ACT_END_TIME));
    int endSlot = Days.daysBetween(new DateTime(getStartDate()), endTime).getDays();
    if (endTime.getHourOfDay() > 0 || endTime.getMinuteOfHour() > 0) {
        ++endSlot;
    }
    return endSlot - slot;
}