Example usage for org.joda.time DateTime withZone

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

Introduction

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

Prototype

public DateTime withZone(DateTimeZone newZone) 

Source Link

Document

Returns a copy of this datetime with a different time zone, preserving the millisecond instant.

Usage

From source file:org.opensextant.extractors.xtemporal.DateNormalization.java

License:Apache License

/**
 * For now this reports only DATE and standard TIME fields. Timezone is
 * still TODO./*  ww  w .j  av  a  2 s  . com*/
 * 
 * TODO: throw NormalizationException
 *
 * @param elements  pattern fields
 * @param dt found date
 * @throws ParseException the parse exception
 */
public static void normalize_date(java.util.Map<String, String> elements, DateMatch dt) throws ParseException {

    // Parse years.
    int year = normalize_year(elements);
    if (year == INVALID_DATE) {
        return;
    }

    if (year > MAXIMUM_YEAR) {
        // HHMM can look like a year, e.g., 2100h or 2300 PM
        return;
    }
    dt.resolution = DateMatch.TimeResolution.YEAR;

    int month = normalize_month(elements);
    if (month == INVALID_DATE) {
        month = normalize_month_name(elements);
    }

    if (month == INVALID_DATE) {
        return;
    }

    DateTime _cal = new DateTime(year, month, 1, 0, 0, DateTimeZone.UTC);

    dt.resolution = DateMatch.TimeResolution.MONTH;

    int dom = normalize_day(elements);
    // If you got this far, then assume Day of Month is 1 (first of the month)
    if (dom == INVALID_DATE) {
        // No date found, resolution is month
        dom = 1;
    } else if (dom == 0) {
        return;
    } else {
        dt.resolution = DateMatch.TimeResolution.DAY;
    }

    // Normalize Time fields found, H, M, s.SSS, etc.
    //
    _cal = _cal.withDayOfMonth(dom);

    // For normal M/D/Y patterns, set the default time to noon, UTC
    // Overall, we want to ensure that the general yyyy-mm-dd form is not impacted
    // by time zone and default hour of 00:00;  -- this generally would yield a date format a day early for ALL US timezones.
    //
    // Time res:  the presence of a field, hh, mm, or ss means the pattern has that level of resolution.
    // So even if time is 00:00:00Z  -- all zeroes -- the resolution is still SECONDS.
    //
    int hour = normalize_time(elements, "hh");
    if (hour >= 0) {
        // Only if HH:MM... is present do we try to detect TZ.
        //
        DateTimeZone tz = normalize_tz(elements);
        if (tz != null) {
            _cal = _cal.withZone(tz);
        }

        // NON-zero hour.
        dt.resolution = DateMatch.TimeResolution.HOUR;
        int min = normalize_time(elements, "mm");
        if (min >= 0) {
            dt.resolution = DateMatch.TimeResolution.MINUTE;
            // NON-zero minutes
            _cal = _cal.withHourOfDay(hour);
            _cal = _cal.withMinuteOfHour(min);
        } else {
            // No minutes
            _cal = _cal.withHourOfDay(hour);
        }

    } else {
        // No hour; default is 12:00 UTC.
        _cal = _cal.withHourOfDay(12);
    }

    dt.datenorm = new Date(_cal.getMillis());
}

From source file:org.opensingular.form.type.core.STypeDateTime.java

License:Apache License

@Override
protected String toStringPersistence(Date originalValue) {
    if (originalValue == null) {
        return null;
    }// w w w .  j  ava  2s.c  o  m
    DateTime instant = new DateTime(originalValue);
    return isoFormarter().print(instant.withZone(DateTimeZone.UTC));
}

From source file:org.opentestsystem.delivery.testreg.persistence.criteria.dependencyresolvers.AssessmentDependencyResolver.java

License:Open Source License

private DateTime resetToStartOfDay(DateTime dateTime) { //Always represent start of the day at the new TimeZone
    return dateTime.withZone(sb11TimeZoneBuilder.getDateTimeZone()).withTimeAtStartOfDay();
}

From source file:org.opentestsystem.delivery.testreg.service.impl.ProctorPackageServiceImpl.java

License:Open Source License

private String doExportProctorPackage(List<String> tenantIds, final DateTime beginTime) {
    xstream.processAnnotations(Assessment.class);
    xstream.alias("Tests", Set.class);
    return xstream.toXML(eligibilityService.findAllAssessmentsByTenantsAndBeginWindow(tenantIds,
            beginTime.withZone(sb11TimeZoneBuilder.getDateTimeZone()))); // Use Configured TZ for TestWindows
}

From source file:org.renjin.primitives.time.Time.java

License:Open Source License

private static DateTime parseIgnoreTrailingCharacters(DateTimeFormatter formatter, String text) {
    // this is a modified version of DateTimeFormatter.parseDateTime() that does not
    // throw an exception on trailing characters

    Chronology chronology = DateTimeUtils.getChronology(null);
    DateTimeParser parser = formatter.getParser();

    Locale locale = null;/* www .  j  a v a2  s .c om*/
    Integer pivotYear = null;
    int defaultYear = 2000;
    DateTimeZone timeZone = null;

    DateTimeParserBucket bucket = new DateTimeParserBucket(0, chronology, locale, pivotYear, defaultYear);
    int newPos = parser.parseInto(bucket, text, 0);
    if (newPos >= 0) {
        long millis = bucket.computeMillis(true, text);
        if (formatter.isOffsetParsed() && bucket.getOffsetInteger() != null) {
            int parsedOffset = bucket.getOffsetInteger();
            DateTimeZone parsedZone = DateTimeZone.forOffsetMillis(parsedOffset);
            chronology = chronology.withZone(parsedZone);
        } else if (bucket.getZone() != null) {
            chronology = chronology.withZone(bucket.getZone());
        }
        DateTime dt = new DateTime(millis, chronology);
        if (timeZone != null) {
            dt = dt.withZone(timeZone);
        }
        return dt;
    }
    throw new IllegalArgumentException();
}

From source file:org.slc.sli.sandbox.idp.saml.SamlResponseComposer.java

License:Apache License

private String createUnsignedResponse(String destination, String issuer, String requestId, String userId,
        Map<String, String> attributes, List<String> roles) {
    String template;//from w w w .  j a va 2s.  c o m
    try {
        template = IOUtils.toString(this.getClass().getResourceAsStream("/samlResponseTemplate.xml"));
    } catch (IOException e) {
        throw new SamlProcessException(e);
    }

    template = template.replace("__RESPONSE_ID__", UUID.randomUUID().toString());
    template = template.replace("__ASSERTION_ID__", UUID.randomUUID().toString());
    template = template.replace("__REQUEST_ID__", requestId);
    template = template.replace("__ISSUE_INSTANT__",
            new DateTime().withZone(DateTimeZone.UTC).toString(ISODateTimeFormat.dateTimeNoMillis()));
    template = template.replace("__DESTINATION__", destination);
    template = template.replace("__ISSUER__", issuer);
    template = template.replace("__TRANSIENT_ID__", UUID.randomUUID().toString()); //must be at least a 128-bit random string
    DateTime notOnOrAfter = new DateTime();
    notOnOrAfter = notOnOrAfter.plusMinutes(10);
    template = template.replace("__NOT_ON_OR_AFTER__",
            notOnOrAfter.withZone(DateTimeZone.UTC).toString(ISODateTimeFormat.dateTimeNoMillis()));

    StringBuilder buf = new StringBuilder();
    addAttribute(buf, "userId", userId);
    if (attributes != null) {
        for (Map.Entry<String, String> attr : attributes.entrySet()) {
            if (attr.getKey() != null && attr.getValue() != null) {
                addAttribute(buf, attr.getKey(), attr.getValue());
            }
        }
    }

    if (roles != null && !roles.isEmpty()) {
        buf.append(ATTRIBUTE_NAME_BEGIN_TEMPLATE.replace("__NAME__", "roles"));
        for (String role : roles) {
            buf.append(ATTRIBUTE_VALUE_TEMPLATE.replace("__VALUE__", role));
        }
        buf.append(ATTRIBUTE_NAME_END_TEMPLATE);
    }

    template = template.replace("__ATTRIBUTES__", buf.toString());
    return template;
}

From source file:org.sleuthkit.autopsy.timeline.ui.detailview.DateAxis.java

License:Open Source License

@Override
protected List<DateTime> calculateTickValues(double length, Object range) {
    List<DateTime> tickDates = new ArrayList<>();
    if (range == null) {
        return tickDates;
    }/*from  www  .  j ava2  s .  c  o m*/
    rangeDivisionInfo = RangeDivisionInfo.getRangeDivisionInfo((Interval) range);
    final DateTime lowerBound1 = getLowerBound();
    final DateTime upperBound1 = getUpperBound();

    if (lowerBound1 == null || upperBound1 == null) {
        return tickDates;
    }
    DateTime lower = lowerBound1.withZone(TimeLineController.getJodaTimeZone());
    DateTime upper = upperBound1.withZone(TimeLineController.getJodaTimeZone());

    DateTime current = lower;
    // Loop as long we exceeded the upper bound.
    while (current.isBefore(upper)) {
        tickDates.add(current);
        current = current.plus(rangeDivisionInfo.getPeriodSize().getPeriod());//.add(interval.interval, interval.amount);
    }

    // At last add the upper bound.
    tickDates.add(upper);

    // If there are at least three dates, check if the gap between the lower date and the second date is at least half the gap of the second and third date.
    // Do the same for the upper bound.
    // If gaps between dates are to small, remove one of them.
    // This can occur, e.g. if the lower bound is 25.12.2013 and years are shown. Then the next year shown would be 2014 (01.01.2014) which would be too narrow to 25.12.2013.
    if (tickDates.size() > 2) {
        DateTime secondDate = tickDates.get(1);
        DateTime thirdDate = tickDates.get(2);
        DateTime lastDate = tickDates.get(tickDates.size() - 2);
        DateTime previousLastDate = tickDates.get(tickDates.size() - 3);

        // If the second date is too near by the lower bound, remove it.
        if (secondDate.getMillis() - lower.getMillis() < (thirdDate.getMillis() - secondDate.getMillis()) / 2) {
            tickDates.remove(lower);
        }

        // If difference from the upper bound to the last date is less than the half of the difference of the previous two dates,
        // we better remove the last date, as it comes to close to the upper bound.
        if (upper.getMillis() - lastDate.getMillis() < (lastDate.getMillis() - previousLastDate.getMillis())
                / 2) {
            tickDates.remove(lastDate);
        }
    }

    if (tickDates.size() >= 2) {
        tickSpacing.set(getDisplayPosition(tickDates.get(1)) - getDisplayPosition(tickDates.get(0)));
    } else if (tickDates.size() >= 4) {
        tickSpacing.set(getDisplayPosition(tickDates.get(2)) - getDisplayPosition(tickDates.get(1)));
    }
    return tickDates;
}

From source file:org.smartdeveloperhub.harvesters.it.backend.DateTimes.java

License:Apache License

static DateTime toUTC(final DateTime timeStamp) {
    return timeStamp == null ? null : timeStamp.withZone(DateTimeZone.UTC);
}

From source file:org.thelq.pircbotx.commands.NewYearsCommand.java

License:Open Source License

protected TreeMultimap<DateTime, DateTimeZone> getNyTimes() {
    synchronized (NEW_YEAR_ZONES) {
        if (NEW_YEAR_ZONES.isEmpty()) {
            NEW_YEAR_ZONES.put(getNow().plusMinutes(6), DateTimeZone.UTC);
        } else if (NEW_YEAR_ZONES.isEmpty())
            //Generate
            for (String curId : DateTimeZone.getAvailableIDs()) {
                DateTimeZone tz = DateTimeZone.forID(curId);

                //Convert new years time relative to UTC
                DateTime nyTime = new DateTime(NEW_YEAR, 1, 1, 0, 0, 0, 0, tz);
                DateTime nyTimeUTC = nyTime.withZone(DateTimeZone.UTC);

                //Add to map
                NEW_YEAR_ZONES.get(nyTimeUTC).add(tz);
            }/*w w w  .  j a  v a2 s . co m*/
        return NEW_YEAR_ZONES;
    }
}

From source file:org.vaadin.spring.samples.mvp.util.SSTimeUtil.java

License:Apache License

/**
 * Get Market start time for current day (i.e., today)
 *
 * @return an org.joda.time.DateTime instance representing the current day
 *         at midnight//from  w w w  .ja v  a  2 s.  c  o  m
 */
public static DateTime getMarketStartDateTime() {
    // Current market date based on now
    DateTime dt = new DateTime();
    dt = dt.withZone(marketTimeZone);
    dt = dt.withMillisOfDay(0); // Set to start of day
    return dt;
}