List of usage examples for org.joda.time DateTimeZone getOffset
public final int getOffset(ReadableInstant instant)
From source file:net.danlew.android.joda.ZoneInfoCompiler.java
License:Apache License
/** * @return false if error.//w ww . jav a 2 s. c om */ static boolean test(String id, DateTimeZone tz) { if (!id.equals(tz.getID())) { return true; } // Test to ensure that reported transitions are not duplicated. long millis = ISOChronology.getInstanceUTC().year().set(0, 1850); long end = ISOChronology.getInstanceUTC().year().set(0, 2050); int offset = tz.getOffset(millis); String key = tz.getNameKey(millis); List<Long> transitions = new ArrayList<Long>(); while (true) { long next = tz.nextTransition(millis); if (next == millis || next > end) { break; } millis = next; int nextOffset = tz.getOffset(millis); String nextKey = tz.getNameKey(millis); if (offset == nextOffset && key.equals(nextKey)) { System.out.println( "*d* Error in " + tz.getID() + " " + new DateTime(millis, ISOChronology.getInstanceUTC())); return false; } if (nextKey == null || (nextKey.length() < 3 && !"??".equals(nextKey))) { System.out.println("*s* Error in " + tz.getID() + " " + new DateTime(millis, ISOChronology.getInstanceUTC()) + ", nameKey=" + nextKey); return false; } transitions.add(Long.valueOf(millis)); offset = nextOffset; key = nextKey; } // Now verify that reverse transitions match up. millis = ISOChronology.getInstanceUTC().year().set(0, 2050); end = ISOChronology.getInstanceUTC().year().set(0, 1850); for (int i = transitions.size(); --i >= 0;) { long prev = tz.previousTransition(millis); if (prev == millis || prev < end) { break; } millis = prev; long trans = transitions.get(i).longValue(); if (trans - 1 != millis) { System.out.println( "*r* Error in " + tz.getID() + " " + new DateTime(millis, ISOChronology.getInstanceUTC()) + " != " + new DateTime(trans - 1, ISOChronology.getInstanceUTC())); return false; } } return true; }
From source file:nodatime.jodadump.JodaDump.java
License:Open Source License
private static void dumpZone(String id, DateTimeZone zone) { // TODO: Reinstate this when Noda Time understands aliases better. // See issue 32 for more details. // if (!id.equals(zone.getID())) { // System.out.println(id + " == " + zone.getID()); // System.out.println(); // return; // }//from w w w.j av a2 s . c o m System.out.println(id); long now = START.getMillis(); while (now < END.getMillis()) { int standardOffset = zone.getStandardOffset(now); int wallOffset = zone.getOffset(now); System.out.printf("%s %s %s%n", INSTANT_FORMAT.print(now), printOffset(standardOffset), printOffset(wallOffset - standardOffset)); // TODO: Output the name when we've got parity in handling // of auto-addition for summer/winter in Noda Time. long next = zone.nextTransition(now); if (next <= now) { break; } now = next; } System.out.println(); }
From source file:nz.al4.airclock.TimeCalculator.java
License:Open Source License
/** * Calculate the current offset from a given time zone * * With thanks to Josh Pinter at http://stackoverflow.com/questions/10900494/ * * @param tz Time zone to get the offset for * @return//from www . j a v a 2s . co m */ public static Integer getTimeZoneOffset(DateTimeZone tz) { Long instant = DateTime.now().getMillis(); long offsetInMilliseconds = tz.getOffset(instant); long minutes = TimeUnit.MILLISECONDS.toMinutes(offsetInMilliseconds); return (int) minutes; }
From source file:org.apache.druid.query.TimewarpOperator.java
License:Apache License
/** * Map time t into the last `period` ending within `dataInterval` * * @param t the current time to be mapped into `dataInterval` * * @return the offset between the mapped time and time t *//*from w w w. j a va 2 s .co m*/ protected long computeOffset(final long t, final DateTimeZone tz) { // start is the beginning of the last period ending within dataInterval long start = dataInterval.getEndMillis() - periodMillis; long startOffset = start % periodMillis - originMillis % periodMillis; if (startOffset < 0) { startOffset += periodMillis; } start -= startOffset; // tOffset is the offset time t within the last period long tOffset = t % periodMillis - originMillis % periodMillis; if (tOffset < 0) { tOffset += periodMillis; } tOffset += start; return tOffset - t - (tz.getOffset(tOffset) - tz.getOffset(t)); }
From source file:org.apache.phoenix.expression.function.ConvertTimezoneFunction.java
License:Apache License
@Override public boolean evaluate(Tuple tuple, ImmutableBytesWritable ptr) { if (!children.get(0).evaluate(tuple, ptr)) { return false; }//from w ww . j ava 2s. c om if (ptr.getLength() == 0) { return true; } long date = PDate.INSTANCE.getCodec().decodeLong(ptr, children.get(0).getSortOrder()); if (!children.get(1).evaluate(tuple, ptr)) { return false; } if (ptr.getLength() == 0) { return true; } DateTimeZone timezoneFrom = JodaTimezoneCache.getInstance(ptr); if (!children.get(2).evaluate(tuple, ptr)) { return false; } if (ptr.getLength() == 0) { return true; } DateTimeZone timezoneTo = JodaTimezoneCache.getInstance(ptr); long convertedDate = date - timezoneFrom.getOffset(date) + timezoneTo.getOffset(date); byte[] outBytes = new byte[8]; PDate.INSTANCE.getCodec().encodeLong(convertedDate, outBytes, 0); ptr.set(outBytes); return true; }
From source file:org.apache.phoenix.expression.function.TimezoneOffsetFunction.java
License:Apache License
@Override public boolean evaluate(Tuple tuple, ImmutableBytesWritable ptr) { if (!children.get(0).evaluate(tuple, ptr)) { return false; }/* w ww . ja v a 2 s.c o m*/ if (ptr.getLength() == 0) { return true; } DateTimeZone timezoneInstance = JodaTimezoneCache.getInstance(ptr); if (!children.get(1).evaluate(tuple, ptr)) { return false; } if (ptr.getLength() == 0) { return true; } long date = PDate.INSTANCE.getCodec().decodeLong(ptr, children.get(1).getSortOrder()); int offset = timezoneInstance.getOffset(date); ptr.set(PInteger.INSTANCE.toBytes(offset / MILLIS_TO_MINUTES)); return true; }
From source file:org.elasticsearch.search.aggregations.bucket.DateRangeIT.java
License:Apache License
public void testSingleValueFieldWithDateMath() throws Exception { DateTimeZone timezone = randomDateTimeZone(); int timeZoneOffset = timezone.getOffset(date(2, 15)); // if time zone is UTC (or equivalent), time zone suffix is "Z", else something like "+03:00", which we get with the "ZZ" format String feb15Suffix = timeZoneOffset == 0 ? "Z" : date(2, 15, timezone).toString("ZZ"); String mar15Suffix = timeZoneOffset == 0 ? "Z" : date(3, 15, timezone).toString("ZZ"); long expectedFirstBucketCount = timeZoneOffset < 0 ? 3L : 2L; SearchResponse response = client().prepareSearch("idx") .addAggregation(dateRange("range").field("date").addUnboundedTo("2012-02-15") .addRange("2012-02-15", "2012-02-15||+1M").addUnboundedFrom("2012-02-15||+1M") .timeZone(timezone)) .execute().actionGet();// w w w . j a va 2 s . co m assertSearchResponse(response); Range range = response.getAggregations().get("range"); assertThat(range, notNullValue()); assertThat(range.getName(), equalTo("range")); List<? extends Bucket> buckets = range.getBuckets(); assertThat(buckets.size(), equalTo(3)); Range.Bucket bucket = buckets.get(0); assertThat(bucket, notNullValue()); assertThat((String) bucket.getKey(), equalTo("*-2012-02-15T00:00:00.000" + feb15Suffix)); assertThat(((DateTime) bucket.getFrom()), nullValue()); assertThat(((DateTime) bucket.getTo()), equalTo(date(2, 15, timezone).toDateTime(DateTimeZone.UTC))); assertThat(bucket.getFromAsString(), nullValue()); assertThat(bucket.getToAsString(), equalTo("2012-02-15T00:00:00.000" + feb15Suffix)); assertThat(bucket.getDocCount(), equalTo(expectedFirstBucketCount)); bucket = buckets.get(1); assertThat(bucket, notNullValue()); assertThat((String) bucket.getKey(), equalTo("2012-02-15T00:00:00.000" + feb15Suffix + "-2012-03-15T00:00:00.000" + mar15Suffix)); assertThat(((DateTime) bucket.getFrom()), equalTo(date(2, 15, timezone).toDateTime(DateTimeZone.UTC))); assertThat(((DateTime) bucket.getTo()), equalTo(date(3, 15, timezone).toDateTime(DateTimeZone.UTC))); assertThat(bucket.getFromAsString(), equalTo("2012-02-15T00:00:00.000" + feb15Suffix)); assertThat(bucket.getToAsString(), equalTo("2012-03-15T00:00:00.000" + mar15Suffix)); assertThat(bucket.getDocCount(), equalTo(2L)); bucket = buckets.get(2); assertThat(bucket, notNullValue()); assertThat((String) bucket.getKey(), equalTo("2012-03-15T00:00:00.000" + mar15Suffix + "-*")); assertThat(((DateTime) bucket.getFrom()), equalTo(date(3, 15, timezone).toDateTime(DateTimeZone.UTC))); assertThat(((DateTime) bucket.getTo()), nullValue()); assertThat(bucket.getFromAsString(), equalTo("2012-03-15T00:00:00.000" + mar15Suffix)); assertThat(bucket.getToAsString(), nullValue()); assertThat(bucket.getDocCount(), equalTo(numDocs - 2L - expectedFirstBucketCount)); }
From source file:org.elasticsearch.search.aggregations.bucket.histogram.DateHistogramAggregationBuilder.java
License:Apache License
DateTimeZone rewriteTimeZone(QueryShardContext context) throws IOException { final DateTimeZone tz = timeZone(); if (field() != null && tz != null && tz.isFixed() == false && field() != null && script() == null) { final MappedFieldType ft = context.fieldMapper(field()); final IndexReader reader = context.getIndexReader(); if (ft != null && reader != null) { Long anyInstant = null; final IndexNumericFieldData fieldData = context.getForField(ft); for (LeafReaderContext ctx : reader.leaves()) { AtomicNumericFieldData leafFD = fieldData.load(ctx); SortedNumericDocValues values = leafFD.getLongValues(); if (values.nextDoc() != DocIdSetIterator.NO_MORE_DOCS) { anyInstant = values.nextValue(); break; }//from ww w . j a va 2 s.c o m } if (anyInstant != null) { final long prevTransition = tz.previousTransition(anyInstant); final long nextTransition = tz.nextTransition(anyInstant); // We need all not only values but also rounded values to be within // [prevTransition, nextTransition]. final long low; DateTimeUnit intervalAsUnit = getIntervalAsDateTimeUnit(); if (intervalAsUnit != null) { final DateTimeField dateTimeField = intervalAsUnit.field(tz); low = dateTimeField.roundCeiling(prevTransition); } else { final TimeValue intervalAsMillis = getIntervalAsTimeValue(); low = Math.addExact(prevTransition, intervalAsMillis.millis()); } // rounding rounds down, so 'nextTransition' is a good upper bound final long high = nextTransition; if (ft.isFieldWithinQuery(reader, low, high, true, false, DateTimeZone.UTC, EPOCH_MILLIS_PARSER, context) == Relation.WITHIN) { // All values in this reader have the same offset despite daylight saving times. // This is very common for location-based timezones such as Europe/Paris in // combination with time-based indices. return DateTimeZone.forOffsetMillis(tz.getOffset(anyInstant)); } } } } return tz; }
From source file:org.graylog2.restclient.lib.DateTools.java
License:Open Source License
public static int getUserTimeZoneOffset(User currentUser) { DateTimeZone tz = globalTimezone; if (currentUser != null && currentUser.getTimeZone() != null) { tz = currentUser.getTimeZone();/*from ww w. j a va 2s .c o m*/ } int offset = tz.getOffset(new DateTime().getMillis()); return ((offset / 1000) / 60) * -1; }
From source file:org.jasig.portlet.calendar.adapter.CalendarEventsDao.java
License:Apache License
/** * Get a JSON-appropriate representation of each recurrence of an event * within the specified time period./*ww w. j a v a2 s . c o m*/ * * @param e * @param interval * @param usersConfiguredDateTimeZone * @return * @throws IOException * @throws URISyntaxException * @throws ParseException */ protected Set<CalendarDisplayEvent> getDisplayEvents(VEvent e, Interval interval, Locale locale, DateTimeZone usersConfiguredDateTimeZone) throws IOException, URISyntaxException, ParseException { final VEvent event = (VEvent) e.copy(); DateTime eventStart; DateTime eventEnd = null; if (event.getStartDate().getTimeZone() == null && !event.getStartDate().isUtc()) { if (log.isDebugEnabled()) { log.debug("Identified event " + event.getSummary() + " as a floating event"); } int offset = usersConfiguredDateTimeZone.getOffset(event.getStartDate().getDate().getTime()); eventStart = new DateTime(event.getStartDate().getDate().getTime() - offset, usersConfiguredDateTimeZone); if (event.getEndDate() != null) { eventEnd = new DateTime(event.getEndDate().getDate().getTime() - offset, usersConfiguredDateTimeZone); } } else { eventStart = new DateTime(event.getStartDate().getDate(), usersConfiguredDateTimeZone); if (event.getEndDate() != null) { eventEnd = new DateTime(event.getEndDate().getDate(), usersConfiguredDateTimeZone); } } if (eventEnd == null) { eventEnd = eventStart; } // Multi-day events may begin in the past; make sure to choose a date in range for the first pass... final Date firstDayToProcess = interval.contains(event.getStartDate().getDate().getTime()) ? event.getStartDate().getDate() : interval.getStart().toDate(); DateMidnight startOfTheSpecificDay = new DateMidnight(firstDayToProcess, usersConfiguredDateTimeZone); DateMidnight endOfTheSpecificDay = startOfTheSpecificDay.plusDays(1); final DateTimeFormatter df = getDateFormatter(locale, usersConfiguredDateTimeZone); final DateTimeFormatter tf = getTimeFormatter(locale, usersConfiguredDateTimeZone); final Set<CalendarDisplayEvent> events = new HashSet<CalendarDisplayEvent>(); final Interval eventInterval = new Interval(eventStart, eventEnd); do { final Interval theSpecificDay = new Interval(startOfTheSpecificDay.getMillis(), endOfTheSpecificDay.getMillis(), usersConfiguredDateTimeZone); /* * Test if the event interval abuts the start of the day or is within the day. * This start time check is needed for the corner case where a zero duration interval * is set for midnight. * The start times are tested directly as opposed to using abuts() because that method * also returns true if the intervals abut at the end of the day. We want to associate * instant events that start at midnight with the starting day, not the ending day. */ if (theSpecificDay.getStart().isEqual(eventStart) || theSpecificDay.overlaps(eventInterval)) { final CalendarDisplayEvent json = new CalendarDisplayEvent(event, eventInterval, theSpecificDay, df, tf); events.add(json); } startOfTheSpecificDay = startOfTheSpecificDay.plusDays(1); endOfTheSpecificDay = endOfTheSpecificDay.plusDays(1); } while (!startOfTheSpecificDay.isAfter(eventEnd) && interval.contains(startOfTheSpecificDay)); return events; }