Example usage for org.joda.time DateTimeZone forOffsetHoursMinutes

List of usage examples for org.joda.time DateTimeZone forOffsetHoursMinutes

Introduction

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

Prototype

public static DateTimeZone forOffsetHoursMinutes(int hoursOffset, int minutesOffset)
        throws IllegalArgumentException 

Source Link

Document

Gets a time zone instance for the specified offset to UTC in hours and minutes.

Usage

From source file:org.elasticsearch.search.facet.datehistogram.DateHistogramFacetParser.java

License:Apache License

private DateTimeZone parseZone(XContentParser parser, XContentParser.Token token) throws IOException {
    if (token == XContentParser.Token.VALUE_NUMBER) {
        return DateTimeZone.forOffsetHours(parser.intValue());
    } else {/* w w  w  . java2s .co m*/
        String text = parser.text();
        int index = text.indexOf(':');
        if (index != -1) {
            int beginIndex = text.charAt(0) == '+' ? 1 : 0;
            // format like -02:30
            return DateTimeZone.forOffsetHoursMinutes(Integer.parseInt(text.substring(beginIndex, index)),
                    Integer.parseInt(text.substring(index + 1)));
        } else {
            // id, listed here: http://joda-time.sourceforge.net/timezones.html
            return DateTimeZone.forID(text);
        }
    }
}

From source file:org.fixb.impl.NativeFixFieldExtractor.java

License:Apache License

private DateTime toDateTime(String value) {
    int[] f = extractTimeFields(value, 6, "UTCTimestamp or TZTimestamp");
    int[] d = extractDateFields(f[0]);
    return new DateTime(d[0], d[1], d[2], f[1], f[2], f[3], DateTimeZone.forOffsetHoursMinutes(f[4], f[5]));
}

From source file:org.jasig.portlet.blackboardvcportlet.dao.impl.ServerConfigurationDaoImpl.java

License:Apache License

@Override
@Transactional/*from  w ww  . j  av a2s . c o  m*/
public ServerConfigurationImpl createOrUpdateConfiguration(
        BlackboardServerConfigurationResponse configurationResponse) {
    ServerConfigurationImpl serverConfiguration = this.getServerConfiguration();
    if (serverConfiguration == null) {
        serverConfiguration = new ServerConfigurationImpl();
    }
    serverConfiguration.onUpdate();

    if (serverConfiguration.getRandomCallbackUrl() == null) {
        //Create random callback URL for blackboard callback
        serverConfiguration.setRandomCallbackUrl(RandomStringUtils.randomAlphanumeric(20));
    }

    serverConfiguration.setBoundaryTime(configurationResponse.getBoundaryTime());
    serverConfiguration.setMaxAvailableTalkers(configurationResponse.getMaxAvailableTalkers());
    serverConfiguration.setMaxAvailableCameras(configurationResponse.getMaxAvailableCameras());
    serverConfiguration.setRaiseHandOnEnter(configurationResponse.isRaiseHandOnEnter());
    serverConfiguration.setMayUseTelephony(configurationResponse.isMayUseTelephony());
    serverConfiguration.setMayUseSecureSignOn(configurationResponse.isMayUseSecureSignOn());
    serverConfiguration.setMustReserveSeats(configurationResponse.isMustReserveSeats());

    final String timeZoneStr = configurationResponse.getTimeZone();
    final Matcher tzMatcher = DATE_TZ_PATTERN.matcher(timeZoneStr);
    if (tzMatcher.matches()) {
        int hours = Integer.parseInt(tzMatcher.group(1));
        int minutes = Integer.parseInt(tzMatcher.group(2));

        final DateTimeZone tz = DateTimeZone.forOffsetHoursMinutes(hours, minutes);
        serverConfiguration.setTimezone(tz);

        logger.debug("Parsed timezone string '{}' to {}", timeZoneStr, tz);
    } else {
        final DateTimeZone tz = DateTimeZone.getDefault();
        serverConfiguration.setTimezone(tz);
        logger.warn("Failed to parse timezone string '{}' defaulting to {}", timeZoneStr, tz);
    }

    this.getEntityManager().persist(serverConfiguration);

    return serverConfiguration;
}

From source file:org.mulgara.util.LexicalDateTime.java

License:Apache License

/** Return a lexical representation of this dateTime. */
public String toString() {
    if (cachedDateTime == null) {
        DateTimeZone dtz;/*  w  ww .  j  a  v a  2 s. co  m*/
        dtz = (localFlag) ? null : DateTimeZone.forOffsetHoursMinutes(tzHours, tzMinutes);
        cachedDateTime = new DateTime(millis, dtz);
    }
    StringBuilder result;
    if (!midnight) {
        result = new StringBuilder(MAIN_FORMATTER.print(cachedDateTime));
        if (milliPlaces > 0) {
            result.append(MILLI_SEPARATOR_STR);
            int place = MILLIS;
            long fraction = millis;
            if (fraction < 0)
                fraction = fraction % place + place;
            for (int m = 0; m < milliPlaces; m++) {
                fraction = fraction % place;
                place /= 10;
                result.append(fraction / place);
            }
        }
    } else {
        result = new StringBuilder(DATE_FORMATTER.print(cachedDateTime.plusDays(-1)));
        result.append(MIDNIGHT_STR);
        if (milliPlaces > 0) {
            result.append(MILLI_SEPARATOR_STR);
            for (int i = 0; i < milliPlaces; i++)
                result.append("0");
        }
    }
    if (!localFlag) {
        if (zuluFlag)
            result.append(ZULU_STR);
        else
            result.append(String.format("%+03d:%02d", tzHours, tzMinutes));
    }
    return result.toString();
}

From source file:org.mulgara.util.LexicalDateTime.java

License:Apache License

/**
 * Parse a dateTime string. It <strong>must</strong> be of the form:
 * ('-')? yyyy '-' MM '-' dd 'T' hh ':' mm ':' ss ( '.' s+ )? ( ( ('+'|'-')? hh ':' mm ) | 'Z' )?
 * @param dt The dateTime string to parse.
 * @return a new LexcalDateTime value./* w  ww. jav a 2  s.  c  o  m*/
 * @throws ParseException If a character that doesn't match the above pattern is discovered.
 */
public static LexicalDateTime parseDateTime(String dt) throws ParseException {
    int pos = 0;
    try {
        boolean negative = dt.charAt(pos) == '-';
        if (negative)
            pos++;
        int year = d(dt, pos++) * 1000 + d(dt, pos++) * 100 + d(dt, pos++) * 10 + d(dt, pos++);
        while (dt.charAt(pos) != DATE_SEPARATOR)
            year = year * 10 + d(dt, pos++);
        if (negative)
            year = -year;
        if (dt.charAt(pos++) != DATE_SEPARATOR)
            throw new ParseException(BAD_FORMAT + "date: " + dt, pos - 1);
        int month = d(dt, pos++) * 10 + d(dt, pos++);
        if (dt.charAt(pos++) != DATE_SEPARATOR)
            throw new ParseException(BAD_FORMAT + "date: " + dt, pos - 1);
        int day = d(dt, pos++) * 10 + d(dt, pos++);

        if (dt.charAt(pos++) != DATE_TIME_SEPARATOR)
            throw new ParseException(BAD_FORMAT + "date/time: " + dt, pos - 1);

        int hour = d(dt, pos++) * 10 + d(dt, pos++);
        if (dt.charAt(pos++) != TIME_SEPARATOR)
            throw new ParseException(BAD_FORMAT + "time: " + dt, pos - 1);
        int minute = d(dt, pos++) * 10 + d(dt, pos++);
        if (dt.charAt(pos++) != TIME_SEPARATOR)
            throw new ParseException(BAD_FORMAT + "time: " + dt, pos - 1);
        int second = d(dt, pos++) * 10 + d(dt, pos++);

        int millisecs = 0;
        byte milliPlaces = 0;
        int lastPos = dt.length() - 1;
        if (pos < lastPos) {
            if (dt.charAt(pos) == MILLI_SEPARATOR) {
                int place = MILLIS / 10;
                int digit;
                while (isDecimal((digit = dt.charAt(++pos) - '0'))) {
                    millisecs += digit * place;
                    if (milliPlaces++ > 3)
                        throw new ParseException(BAD_FORMAT + "milliseconds: " + dt, pos);
                    place /= 10;
                    if (pos == lastPos) {
                        pos++;
                        break;
                    }
                }
            }
        }

        boolean midnightFlag = false;
        if (hour == MIDNIGHT) {
            midnightFlag = true;
            hour = 0;
        }
        if (midnightFlag && (minute > 0 || second > 0 || millisecs > 0))
            throw new ParseException(BAD_FORMAT + "time: " + dt, pos);

        boolean local = false;
        int tzHour = 0;
        int tzMinute = 0;
        boolean zuluFlag = false;
        DateTimeZone timezone = null;
        if (pos <= lastPos) {
            char tz = dt.charAt(pos++);
            if (tz == ZULU) {
                if (pos != lastPos + 1)
                    throw new ParseException(BAD_FORMAT + "timezone: " + dt, pos);
                timezone = UTC;
                zuluFlag = true;
            } else {
                if (pos != lastPos - 4 || (tz != NEG_TZ && tz != POS_TZ))
                    throw new ParseException(BAD_FORMAT + "timezone: " + dt, pos);
                tzHour = d(dt, pos++) * 10 + d(dt, pos++);
                if (dt.charAt(pos++) != TIME_SEPARATOR)
                    throw new ParseException(BAD_FORMAT + "timezone: " + dt, pos - 1);
                tzMinute = d(dt, pos++) * 10 + d(dt, pos++);
                if (tz == NEG_TZ)
                    tzHour = -tzHour;
                timezone = DateTimeZone.forOffsetHoursMinutes(tzHour, tzMinute);
            }
        } else {
            local = true;
        }

        DateTime dateTime = new DateTime(year, month, day, hour, minute, second, millisecs, timezone);
        if (midnightFlag)
            dateTime = dateTime.plusDays(1);
        return new LexicalDateTime(dateTime, tzHour, tzMinute, midnightFlag, milliPlaces, local, zuluFlag);
    } catch (StringIndexOutOfBoundsException e) {
        throw new IllegalArgumentException(BAD_FORMAT + "date: " + dt);
    }
}

From source file:org.openehealth.ipf.commons.ihe.xds.core.metadata.Timestamp.java

License:Apache License

/**
 * Creates a {@link Timestamp} object from the given string.
 * @param s//from  www  . jav  a  2s .c om
 *      String of the pattern <code>YYYY[MM[DD[HH[MM[SS[.S[S[S[S]]]]]]]]][+/-ZZZZ]</code>.
 *      Milliseconds will be ignored.
 * @return
 *      a {@link Timestamp} object, or <code>null</code> if the parameter is <code>null</code> or empty.
 */
public static Timestamp fromHL7(String s) {
    if (StringUtils.isEmpty(s)) {
        return null;
    }

    int pos = Math.max(s.indexOf('-'), s.indexOf('+'));
    int len = (pos >= 0) ? pos : s.length();

    // determine precision
    Precision precision;
    if (len >= 14) {
        precision = Precision.SECOND;
    } else if (len >= 12) {
        precision = Precision.MINUTE;
    } else if (len >= 10) {
        precision = Precision.HOUR;
    } else if (len >= 8) {
        precision = Precision.DAY;
    } else if (len >= 6) {
        precision = Precision.MONTH;
    } else {
        precision = Precision.YEAR;
    }

    // default time zone is UTC
    if (pos < 0) {
        s += "+0000";
    }

    // parse timestamp
    try {
        CommonTS ts = new CommonTS(s);
        DateTime dateTime = new DateTime(ts.getYear(), (ts.getMonth() == 0) ? 1 : ts.getMonth(),
                (ts.getDay() == 0) ? 1 : ts.getDay(), ts.getHour(), ts.getMinute(), ts.getSecond(),
                DateTimeZone.forOffsetHoursMinutes(ts.getGMTOffset() / 100, ts.getGMTOffset() % 100));
        return new Timestamp(dateTime.toDateTime(DateTimeZone.UTC), precision);
    } catch (DataTypeException e) {
        throw new XDSMetaDataException(ValidationMessage.INVALID_TIME, s);
    }
}

From source file:org.phenotips.jodatime.script.JodaTimeScriptService.java

License:Open Source License

/**
 * @param offsetHours the number of hours to offset from UTC, positive or negative integer
 * @param offsetMinutes the number of minutes to offset from UTC, a number between {@code 0} and {@code 59}
 * @return a timezone with the requested offset, or {@code null} if the {@code offsetMinutes} parameter is wrong
 * @see org.joda.time.DateTimeZone#forOffsetHoursMinutes(int, int)
 *///from   w w  w.j a  va2 s  .c om
public DateTimeZone getTimezone(int offsetHours, int offsetMinutes) {
    try {
        return DateTimeZone.forOffsetHoursMinutes(offsetHours, offsetMinutes);
    } catch (IllegalArgumentException ex) {
        return null;
    }
}

From source file:org.springframework.ws.samples.airline.schema.support.SchemaConversionUtils.java

License:Apache License

public static DateTime toDateTime(XMLGregorianCalendar calendar) {
    int timeZoneMinutes = calendar.getTimezone();
    DateTimeZone timeZone = DateTimeZone.forOffsetHoursMinutes(timeZoneMinutes / 60, timeZoneMinutes % 60);
    return new DateTime(calendar.getYear(), calendar.getMonth(), calendar.getDay(), calendar.getHour(),
            calendar.getMinute(), calendar.getSecond(), calendar.getMillisecond(), timeZone);
}

From source file:stroom.dashboard.server.format.DateFormatter.java

License:Apache License

public static DateFormatter create(final FormatSettings settings, final String dateTimeLocale) {
    org.joda.time.format.DateTimeFormatter format = null;

    if (settings != null && settings instanceof DateTimeFormatSettings) {
        final DateTimeFormatSettings dateTimeFormatSettings = (DateTimeFormatSettings) settings;
        String pattern = dateTimeFormatSettings.getPattern();
        if (pattern != null && pattern.trim().length() > 0) {
            final TimeZone timeZone = dateTimeFormatSettings.getTimeZone();
            DateTimeZone zone = DateTimeZone.UTC;

            if (timeZone != null) {
                if (TimeZone.Use.UTC.equals(timeZone.getUse())) {
                    zone = DateTimeZone.UTC;
                } else if (TimeZone.Use.LOCAL.equals(timeZone.getUse())) {
                    pattern = pattern.replaceAll("'Z'", "Z");
                    zone = DateTimeZone.getDefault();

                    try {
                        if (dateTimeLocale != null) {
                            zone = DateTimeZone.forID(dateTimeLocale);
                        }//from  w  w  w .  ja v a  2 s  . c o  m
                    } catch (final IllegalArgumentException e) {
                        // The client time zone was not recognised so we'll
                        // use the default.
                    }

                } else if (TimeZone.Use.ID.equals(timeZone.getUse())) {
                    pattern = pattern.replaceAll("'Z'", "Z");
                    zone = DateTimeZone.forID(timeZone.getId());
                } else if (TimeZone.Use.OFFSET.equals(timeZone.getUse())) {
                    pattern = pattern.replaceAll("'Z'", "Z");
                    zone = DateTimeZone.forOffsetHoursMinutes(getInt(timeZone.getOffsetHours()),
                            getInt(timeZone.getOffsetMinutes()));
                }
            }

            format = DateTimeFormat.forPattern(pattern).withZone(zone);
        }
    }

    return new DateFormatter(format);
}