Example usage for org.joda.time MutableDateTime MutableDateTime

List of usage examples for org.joda.time MutableDateTime MutableDateTime

Introduction

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

Prototype

public MutableDateTime(int year, int monthOfYear, int dayOfMonth, int hourOfDay, int minuteOfHour,
        int secondOfMinute, int millisOfSecond, Chronology chronology) 

Source Link

Document

Constructs an instance from datetime field values using the specified chronology.

Usage

From source file:com.evolveum.midpoint.web.component.DateInput.java

License:Apache License

public Date computeDateTime() {
    Date dateFieldInput = getDate();
    if (dateFieldInput == null) {
        return null;
    }//  w  w w .  jav a  2 s. c om

    Integer hoursInput = getHours();
    Integer minutesInput = getMinutes();
    AM_PM amOrPmInput = getAmOrPm();

    // Get year, month and day ignoring any timezone of the Date object
    Calendar cal = Calendar.getInstance();
    cal.setTime(dateFieldInput);
    int year = cal.get(Calendar.YEAR);
    int month = cal.get(Calendar.MONTH) + 1;
    int day = cal.get(Calendar.DAY_OF_MONTH);
    int hours = (hoursInput == null ? 0 : hoursInput % 24);
    int minutes = (minutesInput == null ? 0 : minutesInput);

    // Use the input to create a date object with proper timezone
    MutableDateTime date = new MutableDateTime(year, month, day, hours, minutes, 0, 0,
            DateTimeZone.forTimeZone(getClientTimeZone()));

    // Adjust for halfday if needed
    if (use12HourFormat()) {
        int halfday = (amOrPmInput == AM_PM.PM ? 1 : 0);
        date.set(DateTimeFieldType.halfdayOfDay(), halfday);
        date.set(DateTimeFieldType.hourOfHalfday(), hours % 12);
    }

    // The date will be in the server's timezone
    return newDateInstance(date.getMillis());
}

From source file:com.foundationdb.server.types.mcompat.mtypes.MDateAndTime.java

License:Open Source License

public static MutableDateTime toJodaDateTime(long[] dt, DateTimeZone dtz) {
    return new MutableDateTime((int) dt[YEAR_INDEX], (int) dt[MONTH_INDEX], (int) dt[DAY_INDEX],
            (int) dt[HOUR_INDEX], (int) dt[MIN_INDEX], (int) dt[SEC_INDEX], 0, dtz);
}

From source file:com.yahoo.bard.webservice.sql.helper.SqlTimeConverter.java

License:Apache License

/**
 * Given an array of strings (a row from a {@link java.sql.ResultSet}) and the
 * {@link Granularity} used to make groupBy statements on time, it will parse out a {@link DateTime}
 * for the row which represents the beginning of the interval it was grouped on.
 *
 * @param offset the last column before the date fields.
 * @param recordValues  The results returned by Sql needed to read the time columns.
 * @param druidQuery  The original druid query which was made using calling
 * {@link #buildGroupBy(RelBuilder, Granularity, String)}.
 *
 * @return the datetime for the start of the interval.
 *//* ww w  .j  ava2 s . co m*/
public DateTime getIntervalStart(int offset, String[] recordValues, DruidAggregationQuery<?> druidQuery) {
    List<SqlDatePartFunction> times = timeGrainToDatePartFunctions(druidQuery.getGranularity());

    DateTimeZone timeZone = getTimeZone(druidQuery);

    if (times.isEmpty()) {
        throw new UnsupportedOperationException("Can't parse dateTime for if no times were grouped on.");
    }

    MutableDateTime mutableDateTime = new MutableDateTime(0, 1, 1, 0, 0, 0, 0, timeZone);

    for (int i = 0; i < times.size(); i++) {
        int value = Integer.parseInt(recordValues[offset + i]);
        SqlDatePartFunction fn = times.get(i);
        setDateTime(value, fn, mutableDateTime);
    }

    return mutableDateTime.toDateTime();
}

From source file:jais.messages.StaticAndVoyageRelatedData.java

License:Apache License

/**
 *
 * @return/*from w  ww  . j a v a2  s .c o  m*/
 */
public MutableDateTime getETA() {
    StringBuilder eta = new StringBuilder();
    MutableDateTime dt = MutableDateTime.now();
    int year = dt.getYear();
    int month = dt.getMonthOfYear();

    if (_month > 0) {
        // properly formatted month
        if (_month < 10) {
            eta.append("0").append(_month);
        } else if (_month > 12) {
            eta.append("12");
            _month = 12; // use this to validate the days later
        } else {
            eta.append(_month);
        }
        eta.append("/");

        // assume next year
        if (_month < month) {
            year++;
        }

        // prepend datetime string with YYYY/
        eta.insert(0, year).insert(4, "/");

        // recreate the Calendar object based on the validated month
        dt = new MutableDateTime(year, _month, 1, 0, 0, 0, 0, DateTimeZone.UTC);

        // Get the number of days in that month
        int daysInMonth = dt.monthOfYear().getMaximumValue();

        // properly formatted day
        if (_day < 1) {
            eta.append("01");
        } else if (_day < 10) {
            eta.append("0").append(_day);
        } else if (_day >= daysInMonth) {
            eta.append(daysInMonth);
        } else {
            eta.append(_day);
        }
        eta.append(" ");

        // properly formatted hour
        if (_hour < 1) {
            eta.append("00");
        } else if (_hour < 10) {
            eta.append("0").append(_hour);
        } else if (_hour >= 24) {
            eta.append(00);
        } else {
            eta.append(_hour);
        }
        eta.append(":");

        // properly formatted minute
        if (_minute < 1 || _minute > 59) {
            eta.append("00");
        } else if (_minute < 10) {
            eta.append("0").append(_minute);
        } else {
            eta.append(_minute);
        }
    } else {
        // default to epoch if month is invalid
        eta.append("1970/01/01 00:00");
    }

    try {
        dt = MutableDateTime.parse(eta.toString(), ETA_FORMATTER);
    } catch (Exception e) {
        LOG.warn("Invalid ETA, setting to epoch");
        dt = MutableDateTime.parse("1970/01/01 00:00", ETA_FORMATTER);
    }

    return dt;
}

From source file:net.solarnetwork.central.dras.mock.biz.MockDRASObserverBiz.java

License:Open Source License

public MockDRASObserverBiz() {
    TimeZone tz = TimeZone.getTimeZone("Pacific/Auckland");

    uniLocation = new SolarLocation();
    uniLocation.setId(counter.decrementAndGet());
    uniLocation.setCountry("NZ");
    uniLocation.setCreated(new DateTime());
    uniLocation.setName("Mock Location");
    uniLocation.setRegion("UNI");
    uniLocation.setTimeZoneId(tz.getID());
    uniLocation.setLatitude(groupLatitude);
    uniLocation.setLongitude(groupLongitude);

    uniLocations = new LinkedHashMap<Long, SolarLocation>();
    uniLocations.put(uniLocation.getId(), uniLocation);

    uniGroups = new ArrayList<SolarNodeGroup>(numGroups);
    addGroup(new SolarNodeGroup(counter.decrementAndGet(), uniLocation.getId(), "Mock Group A"));
    addGroup(new SolarNodeGroup(counter.decrementAndGet(), uniLocation.getId(), "Mock Group B"));
    participantGroups = new ArrayList<CapabilityInformation>(numGroups);
    for (SolarNodeGroup group : uniGroups) {
        SimpleCapabilityInformation groupInfo = new SimpleCapabilityInformation();
        groupInfo.setId(group.getId());/*from   w w w. j  av a 2  s  .c o  m*/
        groupInfo.setLocation(uniLocation);
        groupInfo.setGenerationCapacityWatts(participantGenerationCapacity);
        groupInfo.setStorageCapacityWattHours(participantStorageCapacity);
        participantGroups.add(groupInfo);
    }

    uniProgramParticipants = new LinkedHashSet<Identity<Long>>(numNodes);
    participantGroupMemebers = new LinkedHashMap<Long, Set<CapabilityInformation>>(numGroups);
    for (int i = 0; i < numNodes; i++) {
        SolarNode participant = new SolarNode(counter.decrementAndGet(), createRandomLocation().getId());
        uniProgramParticipants.add(participant);
        int groupIndex = (i % numGroups);
        SimpleCapabilityInformation group = (SimpleCapabilityInformation) participantGroups.get(groupIndex);
        Set<CapabilityInformation> groupMembers = participantGroupMemebers.get(group.getId());
        if (groupMembers == null) {
            groupMembers = new LinkedHashSet<CapabilityInformation>(numNodes);
            participantGroupMemebers.put(group.getId(), groupMembers);
        }
        SimpleCapabilityInformation info = new SimpleCapabilityInformation();
        info.setId(participant.getId());
        info.setLocation(uniLocations.get(participant.getLocationId()));
        info.setGenerationCapacityWatts(participantGenerationCapacity);
        info.setStorageCapacityWattHours(participantStorageCapacity);
        groupMembers.add(info);
        group.addGenerationCapacityWatts(participantGenerationCapacity);
        group.addStorageCapacityWattHours(participantStorageCapacity);
    }
    uniProgram = new Program(counter.decrementAndGet(), "UNI Program", 1);

    MutableDateTime mdt = new MutableDateTime(2011, 1, 1, 8, 0, 0, 0, DateTimeZone.forTimeZone(tz));
    uniEvents = new ArrayList<Event>(numEvents);
    uniEventParticipants = new LinkedHashMap<Long, EventParticipants>(numEvents);
    uniEventTargets = new LinkedHashMap<Long, EventTargets>(numEvents);

    EventRule eventRule = new EventRule(counter.decrementAndGet(), EventRule.RuleKind.LOAD_AMOUNT,
            EventRule.ScheduleKind.DYNAMIC);
    addEventRule(eventRule);

    for (int i = 0; i < numEvents; i++) {
        Event event = new Event(counter.decrementAndGet(), uniProgram.getId(),
                String.format("Mock Event %d", (i + 1)), mdt.toDateTime(),
                mdt.toDateTime().plus(Period.hours(2)));

        Set<Identity<Long>> groupSet = new LinkedHashSet<Identity<Long>>(2);
        switch (i % 3) {
        case 0:
            groupSet.add(participantGroups.get(0));
            break;

        case 1:
            groupSet.add(participantGroups.get(1));
            break;

        case 2:
            groupSet.add(participantGroups.get(0));
            groupSet.add(participantGroups.get(1));
            break;
        }
        EventParticipants ep = new EventParticipants(counter.decrementAndGet(), event.getId(), null, groupSet);
        uniEventParticipants.put(event.getId(), ep);

        // give each event a load shed target of 1kW
        EventTargets et = new EventTargets(counter.decrementAndGet(), eventRule.getId(),
                new TreeSet<EventTarget>(Arrays.asList(new EventTarget(Duration.ZERO, 1000D))));

        addEvent(event, ep, et);
        mdt.addWeeks(1);
    }
}

From source file:org.apache.wicket.extensions.yui.calendar.DateTimeField.java

License:Apache License

/**
 * Sets the converted input, which is an instance of {@link Date}, possibly null. It combines
 * the inputs of the nested date, hours, minutes and am/pm fields and constructs a date from it.
 * <p>/*ww  w.j a  v  a  2s.  c  om*/
 * Note that overriding this method is a better option than overriding {@link #updateModel()}
 * like the first versions of this class did. The reason for that is that this method can be
 * used by form validators without having to depend on the actual model being updated, and this
 * method is called by the default implementation of {@link #updateModel()} anyway (so we don't
 * have to override that anymore).
 */
@Override
protected void convertInput() {
    try {
        // Get the converted input values
        Date dateFieldInput = dateField.getConvertedInput();
        Integer hoursInput = hoursField.getConvertedInput();
        Integer minutesInput = minutesField.getConvertedInput();
        AM_PM amOrPmInput = amOrPmChoice.getConvertedInput();

        if (dateFieldInput == null) {
            return;
        }

        // Get year, month and day ignoring any timezone of the Date object
        Calendar cal = Calendar.getInstance();
        cal.setTime(dateFieldInput);
        int year = cal.get(Calendar.YEAR);
        int month = cal.get(Calendar.MONTH) + 1;
        int day = cal.get(Calendar.DAY_OF_MONTH);
        int hours = (hoursInput == null ? 0 : hoursInput % 24);
        int minutes = (minutesInput == null ? 0 : minutesInput);

        // Use the input to create a date object with proper timezone
        MutableDateTime date = new MutableDateTime(year, month, day, hours, minutes, 0, 0,
                DateTimeZone.forTimeZone(getClientTimeZone()));

        // Adjust for halfday if needed
        if (use12HourFormat()) {
            int halfday = (amOrPmInput == AM_PM.PM ? 1 : 0);
            date.set(DateTimeFieldType.halfdayOfDay(), halfday);
            date.set(DateTimeFieldType.hourOfHalfday(), hours % 12);
        }

        // The date will be in the server's timezone
        setConvertedInput(new Date(date.getMillis()));
    } catch (RuntimeException e) {
        DateTimeField.this.error(e.getMessage());
        invalid();
    }
}

From source file:org.codelibs.elasticsearch.common.joda.DateMathParser.java

License:Apache License

private long parseDateTime(String value, DateTimeZone timeZone, boolean roundUpIfNoTime) {
    DateTimeFormatter parser = dateTimeFormatter.parser();
    if (timeZone != null) {
        parser = parser.withZone(timeZone);
    }/*from w  w  w  .ja  v  a  2  s . c om*/
    try {
        MutableDateTime date;
        // We use 01/01/1970 as a base date so that things keep working with date
        // fields that are filled with times without dates
        if (roundUpIfNoTime) {
            date = new MutableDateTime(1970, 1, 1, 23, 59, 59, 999, DateTimeZone.UTC);
        } else {
            date = new MutableDateTime(1970, 1, 1, 0, 0, 0, 0, DateTimeZone.UTC);
        }
        final int end = parser.parseInto(date, value, 0);
        if (end < 0) {
            int position = ~end;
            throw new IllegalArgumentException("Parse failure at index [" + position + "] of [" + value + "]");
        } else if (end != value.length()) {
            throw new IllegalArgumentException(
                    "Unrecognized chars at the end of [" + value + "]: [" + value.substring(end) + "]");
        }
        return date.getMillis();
    } catch (IllegalArgumentException e) {
        throw new ElasticsearchParseException("failed to parse date field [{}] with format [{}]", e, value,
                dateTimeFormatter.format());
    }
}

From source file:org.elasticsearch.common.joda.DateMathParser.java

License:Apache License

private long parseRoundCeilStringValue(String value) {
    try {/*from   w ww . ja  v a2  s .co m*/
        // we create a date time for inclusive upper range, we "include" by default the day level data
        // so something like 2011-01-01 will include the full first day of 2011.
        // we also use 1970-01-01 as the base for it so we can handle searches like 10:12:55 (just time)
        // since when we index those, the base is 1970-01-01
        MutableDateTime dateTime = new MutableDateTime(1970, 1, 1, 23, 59, 59, 999, DateTimeZone.UTC);
        int location = dateTimeFormatter.parser().parseInto(dateTime, value, 0);
        // if we parsed all the string value, we are good
        if (location == value.length()) {
            return dateTime.getMillis();
        }
        // if we did not manage to parse, or the year is really high year which is unreasonable
        // see if its a number
        if (location <= 0 || dateTime.getYear() > 5000) {
            try {
                long time = Long.parseLong(value);
                return timeUnit.toMillis(time);
            } catch (NumberFormatException e1) {
                throw new ElasticsearchParseException(
                        "failed to parse date field [" + value + "], tried both date format ["
                                + dateTimeFormatter.format() + "], and timestamp number");
            }
        }
        return dateTime.getMillis();
    } catch (RuntimeException e) {
        try {
            long time = Long.parseLong(value);
            return timeUnit.toMillis(time);
        } catch (NumberFormatException e1) {
            throw new ElasticsearchParseException("failed to parse date field [" + value
                    + "], tried both date format [" + dateTimeFormatter.format() + "], and timestamp number",
                    e);
        }
    }
}

From source file:org.wicketstuff.datetime.extensions.yui.calendar.DateTimeField.java

License:Apache License

/**
 * Sets the converted input, which is an instance of {@link Date}, possibly null. It combines
 * the inputs of the nested date, hours, minutes and am/pm fields and constructs a date from it.
 * <p>//w ww  .  j a  v a  2 s  .c o m
 * Note that overriding this method is a better option than overriding {@link #updateModel()}
 * like the first versions of this class did. The reason for that is that this method can be
 * used by form validators without having to depend on the actual model being updated, and this
 * method is called by the default implementation of {@link #updateModel()} anyway (so we don't
 * have to override that anymore).
 */
@Override
public void convertInput() {
    try {
        // Get the converted input values
        Date dateFieldInput = dateField.getConvertedInput();
        Integer hoursInput = hoursField.getConvertedInput();
        Integer minutesInput = minutesField.getConvertedInput();
        AM_PM amOrPmInput = amOrPmChoice.getConvertedInput();

        if (dateFieldInput == null) {
            return;
        }

        // Get year, month and day ignoring any timezone of the Date object
        Calendar cal = Calendar.getInstance();
        cal.setTime(dateFieldInput);
        int year = cal.get(Calendar.YEAR);
        int month = cal.get(Calendar.MONTH) + 1;
        int day = cal.get(Calendar.DAY_OF_MONTH);
        int hours = (hoursInput == null ? 0 : hoursInput % 24);
        int minutes = (minutesInput == null ? 0 : minutesInput);

        // Use the input to create a date object with proper timezone
        MutableDateTime date = new MutableDateTime(year, month, day, hours, minutes, 0, 0,
                DateTimeZone.forTimeZone(getClientTimeZone()));

        // Adjust for halfday if needed
        if (use12HourFormat()) {
            int halfday = (amOrPmInput == AM_PM.PM ? 1 : 0);
            date.set(DateTimeFieldType.halfdayOfDay(), halfday);
            date.set(DateTimeFieldType.hourOfHalfday(), hours % 12);
        }

        // The date will be in the server's timezone
        setConvertedInput(newDateInstance(date.getMillis()));
    } catch (RuntimeException e) {
        DateTimeField.this.error(e.getMessage());
        invalid();
    }
}