private String reformatFerretToISO(String in) { Chronology chrono = GregorianChronology.getInstance(DateTimeZone.UTC); DateTimeFormatter iso = ISODateTimeFormat.dateTime().withChronology(chrono).withZone(DateTimeZone.UTC);; DateTimeFormatter sFerretForm = DateTimeFormat.forPattern("dd-MMM-yyyy").withChronology(chrono).withZone(DateTimeZone.UTC); DateTimeFormatter lFerretForm = DateTimeFormat.forPattern("dd-MMM-yyyy HH:mm").withChronology(chrono).withZone(DateTimeZone.UTC); DateTime td; try { td = lFerretForm.parseDateTime(in).withZone(DateTimeZone.UTC).withChronology(chrono); } catch (Exception e) { try { td = sFerretForm.parseDateTime(in).withZone(DateTimeZone.UTC).withChronology(chrono); } catch (Exception e2) { return null; } } if ( td != null ) { return iso.print(td.getMillis()); } else { return null; } }
/** * Calculates the number of whole units between the two specified partial datetimes. * <p> * The two partials must contain the same fields, for example you can specify * two <code>LocalDate</code> objects. * * @param start the start partial date, validated to not be null * @param end the end partial date, validated to not be null * @param zeroInstance the zero instance constant, must not be null * @return the period * @throws IllegalArgumentException if the partials are null or invalid */ protected static int between(ReadablePartial start, ReadablePartial end, ReadablePeriod zeroInstance) { if (start == null || end == null) { throw new IllegalArgumentException("ReadablePartial objects must not be null"); } if (start.size() != end.size()) { throw new IllegalArgumentException("ReadablePartial objects must have the same set of fields"); } for (int i = 0, isize = start.size(); i < isize; i++) { if (start.getFieldType(i) != end.getFieldType(i)) { throw new IllegalArgumentException("ReadablePartial objects must have the same set of fields"); } } if (DateTimeUtils.isContiguous(start) == false) { throw new IllegalArgumentException("ReadablePartial objects must be contiguous"); } Chronology chrono = DateTimeUtils.getChronology(start.getChronology()).withUTC(); int[] values = chrono.get(zeroInstance, chrono.set(start, 0L), chrono.set(end, 0L)); return values[0]; }
/** * Creates a new instance representing the number of complete standard length units * in the specified period. * <p> * This factory method converts all fields from the period to hours using standardised * durations for each field. Only those fields which have a precise duration in * the ISO UTC chronology can be converted. * <ul> * <li>One week consists of 7 days. * <li>One day consists of 24 hours. * <li>One hour consists of 60 minutes. * <li>One minute consists of 60 seconds. * <li>One second consists of 1000 milliseconds. * </ul> * Months and Years are imprecise and periods containing these values cannot be converted. * * @param period the period to get the number of hours from, must not be null * @param millisPerUnit the number of milliseconds in one standard unit of this period * @throws IllegalArgumentException if the period contains imprecise duration values */ protected static int standardPeriodIn(ReadablePeriod period, long millisPerUnit) { if (period == null) { return 0; } Chronology iso = ISOChronology.getInstanceUTC(); long duration = 0L; for (int i = 0; i < period.size(); i++) { int value = period.getValue(i); if (value != 0) { DurationField field = period.getFieldType(i).getField(iso); if (field.isPrecise() == false) { throw new IllegalArgumentException( "Cannot convert period to duration as " + field.getName() + " is not precise in the period " + period); } duration = FieldUtils.safeAdd(duration, FieldUtils.safeMultiply(field.getUnitMillis(), value)); } } return FieldUtils.safeToInt(duration / millisPerUnit); }
private static long parseFullInstant(String input, final Chronology chrono) { for (final DateTimeParser p : full) { final DateTimeParserBucket bucket = new DateTimeParserBucket(0, chrono, null, null, 2000); try { p.parseInto(bucket, input, 0); } catch (IllegalArgumentException e) { // pass-through continue; } return bucket.computeMillis(); } throw new IllegalArgumentException(input + " is not a valid instant"); }
private static long parseTodayInstant(String input, final Chronology chrono, long now) { final DateTime n = new DateTime(now, chrono); for (final DateTimeParser p : today) { final DateTimeParserBucket bucket = new DateTimeParserBucket(0, chrono, null, null, 2000); bucket.saveField(chrono.year(), n.getYear()); bucket.saveField(chrono.monthOfYear(), n.getMonthOfYear()); bucket.saveField(chrono.dayOfYear(), n.getDayOfYear()); try { p.parseInto(bucket, input, 0); } catch (IllegalArgumentException e) { // pass-through continue; } return bucket.computeMillis(); } throw new IllegalArgumentException(input + " is not a valid instant"); }
public long getDateTimeMillis( int year, int monthOfYear, int dayOfMonth, int hourOfDay, int minuteOfHour, int secondOfMinute, int millisOfSecond) throws IllegalArgumentException { Chronology base; if ((base = getBase()) != null) { return base.getDateTimeMillis(year, monthOfYear, dayOfMonth, hourOfDay, minuteOfHour, secondOfMinute, millisOfSecond); } FieldUtils.verifyValueBounds(DateTimeFieldType.hourOfDay(), hourOfDay, 0, 23); FieldUtils.verifyValueBounds(DateTimeFieldType.minuteOfHour(), minuteOfHour, 0, 59); FieldUtils.verifyValueBounds(DateTimeFieldType.secondOfMinute(), secondOfMinute, 0, 59); FieldUtils.verifyValueBounds(DateTimeFieldType.millisOfSecond(), millisOfSecond, 0, 999); return getDateMidnightMillis(year, monthOfYear, dayOfMonth) + hourOfDay * DateTimeConstants.MILLIS_PER_HOUR + minuteOfHour * DateTimeConstants.MILLIS_PER_MINUTE + secondOfMinute * DateTimeConstants.MILLIS_PER_SECOND + millisOfSecond; }
/** * If month-day is 02-29 and year isn't leap, advances to next leap year. */ private long setDayOfMonthNext(Chronology chrono, long next) { try { next = setDayOfMonth(chrono, next); } catch (IllegalArgumentException e) { if (iMonthOfYear == 2 && iDayOfMonth == 29) { while (chrono.year().isLeap(next) == false) { next = chrono.year().add(next, 1); } next = setDayOfMonth(chrono, next); } else { throw e; } } return next; }
private long setDayOfWeek(Chronology chrono, long instant) { int dayOfWeek = chrono.dayOfWeek().get(instant); int daysToAdd = iDayOfWeek - dayOfWeek; if (daysToAdd != 0) { if (iAdvance) { if (daysToAdd < 0) { daysToAdd += 7; } } else { if (daysToAdd > 0) { daysToAdd -= 7; } } instant = chrono.dayOfWeek().add(instant, daysToAdd); } return instant; }
/** * Gets the chronology, which is the GJChronology if a GregorianCalendar is used, * BuddhistChronology if a BuddhistCalendar is used or ISOChronology otherwise. * The time zone specified is used in preference to that on the calendar. * * @param object the Calendar to convert, must not be null * @param zone the specified zone to use, null means default zone * @return the chronology, never null * @throws NullPointerException if the object is null * @throws ClassCastException if the object is an invalid type */ public Chronology getChronology(Object object, DateTimeZone zone) { if (object.getClass().getName().endsWith(".BuddhistCalendar")) { return BuddhistChronology.getInstance(zone); } else if (object instanceof GregorianCalendar) { GregorianCalendar gc = (GregorianCalendar) object; long cutover = gc.getGregorianChange().getTime(); if (cutover == Long.MIN_VALUE) { return GregorianChronology.getInstance(zone); } else if (cutover == Long.MAX_VALUE) { return JulianChronology.getInstance(zone); } else { return GJChronology.getInstance(zone, cutover, 4); } } else { return ISOChronology.getInstance(zone); } }
public long getDateTimeMillis(int year, int monthOfYear, int dayOfMonth, int millisOfDay) throws IllegalArgumentException { Chronology base; if ((base = getBase()) != null) { return base.getDateTimeMillis(year, monthOfYear, dayOfMonth, millisOfDay); } // Assume date is Gregorian. long instant = iGregorianChronology.getDateTimeMillis (year, monthOfYear, dayOfMonth, millisOfDay); if (instant < iCutoverMillis) { // Maybe it's Julian. instant = iJulianChronology.getDateTimeMillis (year, monthOfYear, dayOfMonth, millisOfDay); if (instant >= iCutoverMillis) { // Okay, it's in the illegal cutover gap. throw new IllegalArgumentException("Specified date does not exist"); } } return instant; }
public PointInTime parsePointInTime(String text) { if (getParser() == null) { throw new UnsupportedOperationException("Parsing not supported"); } text = truncateTimeZone(text); Chronology chrono = selectChronology(); PointInTimeParserBucket bucket = new PointInTimeParserBucket(0, chrono, getLocale()); int newPos = getParser().parseInto(bucket, text, 0); if (newPos >= 0) { if (newPos >= text.length()) { ReadablePartial partial = bucket.toPartial(); return new PointInTime(partial); } } else { newPos = ~newPos; } throw new IllegalArgumentException(createErrorMessage(text, newPos)); }
/** * Wraps another chronology, with datetime limits. When withUTC or * withZone is called, the returned LimitChronology instance has * the same limits, except they are time zone adjusted. * * @param base base chronology to wrap * @param lowerLimit inclusive lower limit, or null if none * @param upperLimit exclusive upper limit, or null if none * @throws IllegalArgumentException if chronology is null or limits are invalid */ public static LimitChronology getInstance(Chronology base, ReadableDateTime lowerLimit, ReadableDateTime upperLimit) { if (base == null) { throw new IllegalArgumentException("Must supply a chronology"); } lowerLimit = lowerLimit == null ? null : lowerLimit.toDateTime(); upperLimit = upperLimit == null ? null : upperLimit.toDateTime(); if (lowerLimit != null && upperLimit != null) { if (!lowerLimit.isBefore(upperLimit)) { throw new IllegalArgumentException ("The lower limit must be come before than the upper limit"); } } return new LimitChronology(base, (DateTime)lowerLimit, (DateTime)upperLimit); }
/** * We adjust the instant by displayOffset to adjust for the offset that might have been added in * {@link DateTimeFormatter#printTo(Appendable, long, Chronology)} when using a time zone. */ @Override public void printTo(StringBuffer buf, long instant, Chronology chrono, int displayOffset, DateTimeZone displayZone, Locale locale) { if (hasMilliSecondPrecision) { buf.append(instant - displayOffset); } else { buf.append((instant - displayOffset) / 1000); } }
/** * We adjust the instant by displayOffset to adjust for the offset that might have been added in * {@link DateTimeFormatter#printTo(Appendable, long, Chronology)} when using a time zone. */ @Override public void printTo(Writer out, long instant, Chronology chrono, int displayOffset, DateTimeZone displayZone, Locale locale) throws IOException { if (hasMilliSecondPrecision) { out.write(String.valueOf(instant - displayOffset)); } else { out.append(String.valueOf((instant - displayOffset) / 1000)); } }
public RangeDataPointAggregator(DataPointGroup innerDataPointGroup, RangeSubAggregator subAggregator) { super(innerDataPointGroup); m_subAggregator = subAggregator; m_dpIterator = new ArrayList<DataPoint>().iterator(); Chronology chronology = GregorianChronology.getInstance(m_timeZone); TimeUnit tu = m_sampling.getUnit(); switch (tu) { case YEARS: m_unitField = chronology.year(); break; case MONTHS: m_unitField = chronology.monthOfYear(); break; case WEEKS: m_unitField = chronology.weekOfWeekyear(); break; case DAYS: m_unitField = chronology.dayOfMonth(); break; case HOURS: m_unitField = chronology.hourOfDay(); break; case MINUTES: m_unitField = chronology.minuteOfHour(); break; case SECONDS: m_unitField = chronology.secondOfDay(); break; default: m_unitField = chronology.millisOfSecond(); break; } }
/** * Gets the Chronology in a specific time zone. * * @param zone the zone to get the chronology in, null is default * @return the chronology */ public Chronology withZone(DateTimeZone zone) { if (zone == null) { zone = DateTimeZone.getDefault(); } if (zone == getZone()) { return this; } return getInstance(zone); }
public static void main(String[] args) { Chronology al = All360Chronology.getInstance(DateTimeZone.UTC); DateTime dt = new DateTime(1999, 2, 27, 0, 0, 0, 0, al).withZone(DateTimeZone.UTC); DateTimeFormatter fmt = DateTimeFormat.forPattern("yyyy-MM-dd HH:mm:ss"); for ( int i = 0; i < 1000; i++ ) { System.out.println(fmt.print(dt.plusDays(i))); } }
public static void main(String[] args) { Chronology al = AllLeapChronology.getInstance(DateTimeZone.UTC); DateTime dt = new DateTime(1999, 2, 27, 0, 0, 0, 0, al).withZone(DateTimeZone.UTC); DateTimeFormatter fmt = DateTimeFormat.forPattern("yyyy-MM-dd HH:mm:ss"); for ( int i = 0; i < 10; i++ ) { System.out.println(fmt.print(dt.plusDays(i))); } }
public static void main(String[] args) { Chronology nl = NoLeapChronology.getInstance(DateTimeZone.UTC); DateTimeFormatter fmt = DateTimeFormat.forPattern("yyyy-MM-dd HH:mm:ss"); DateTime dt = new DateTime(2000, 2, 27, 0, 0, 0, 0, nl); for ( int i = 0; i < 10; i++ ) { System.out.println(fmt.print(dt.plusDays(i))); } }
/** * Converts dateUnit to Joda-Time DateTime with a specific chronology. * * @param chronology Chronology to use * @return Populated DateTime object */ public DateTime toJodaDateTime( Chronology chronology ) { try { return new DateTime( year, month, day, hour, minute, second, millis, chronology.withZone( DateTimeZone.forTimeZone( timeZone ) ) ); } catch ( IllegalInstantException ex ) { LocalDateTime localDateTime = new LocalDateTime( year, month, day, hour, minute, second, millis, chronology.withZone( DateTimeZone.forTimeZone( timeZone ) ) ); return localDateTime.toLocalDate().toDateTimeAtStartOfDay(); } }
@Override public void printTo(Writer out, long instant, Chronology chrono, int displayOffset, DateTimeZone displayZone, Locale locale) throws IOException { int value = getValue(instant, chrono); if (value < 0) { if (fillChar != null) { out.write(fillChar); out.write(fillChar); } } else { super.printTo(out, instant, chrono, displayOffset, displayZone, locale); } }
public Chronology withUTC() { if (iWithUTC == null) { if (getZone() == DateTimeZone.UTC) { iWithUTC = this; } else { iWithUTC = LenientChronology.getInstance(getBase().withUTC()); } } return iWithUTC; }
/** * Constructs an interval from a time period and an end instant. * <p> * When forming the interval, the chronology from the instant is used * if present, otherwise the chronology of the period is used. * * @param period the period of this interval, null means zero length * @param end end of this interval, null means now * @throws IllegalArgumentException if the end is before the start * @throws ArithmeticException if the start instant exceeds the capacity of a long */ protected BaseInterval(ReadablePeriod period, ReadableInstant end) { super(); Chronology chrono = DateTimeUtils.getInstantChronology(end); iChronology = chrono; iEndMillis = DateTimeUtils.getInstantMillis(end); if (period == null) { iStartMillis = iEndMillis; } else { iStartMillis = chrono.add(period, iEndMillis, -1); } checkInterval(iStartMillis, iEndMillis); }
/** * Gets the Chronology in a specific time zone. * * @param zone the zone to get the chronology in, null is default * @return the chronology */ public Chronology withZone(DateTimeZone zone) { if (zone == null) { zone = DateTimeZone.getDefault(); } if (zone == getZone()) { return this; } return getInstance(zone, iCutoverInstant, getMinimumDaysInFirstWeek()); }
public Chronology withZone(DateTimeZone zone) { if (zone == null) { zone = DateTimeZone.getDefault(); } if (zone == getParam()) { return this; } if (zone == DateTimeZone.UTC) { return getBase(); } return new ZonedChronology(getBase(), zone); }
protected int getValue(long instant, Chronology chrono) { try { int value = type.getField(chrono).get(instant); if (value < 0) { value = -value; } return value; } catch (RuntimeException e) { return -1; } }
public long getDateTimeMillis( int year, int monthOfYear, int dayOfMonth, int millisOfDay) throws IllegalArgumentException { Chronology base; if ((base = getBase()) != null) { return base.getDateTimeMillis(year, monthOfYear, dayOfMonth, millisOfDay); } FieldUtils.verifyValueBounds (DateTimeFieldType.millisOfDay(), millisOfDay, 0, DateTimeConstants.MILLIS_PER_DAY - 1); return getDateMidnightMillis(year, monthOfYear, dayOfMonth) + millisOfDay; }
/** * Creates a period from the given interval endpoints. * * @param startInstant interval start, null means now * @param endInstant interval end, null means now * @param type which set of fields this period supports, null means standard * @throws IllegalArgumentException if period type is invalid */ protected BasePeriod(ReadableInstant startInstant, ReadableInstant endInstant, PeriodType type) { super(); type = checkPeriodType(type); if (startInstant == null && endInstant == null) { iType = type; iValues = new int[size()]; } else { long startMillis = DateTimeUtils.getInstantMillis(startInstant); long endMillis = DateTimeUtils.getInstantMillis(endInstant); Chronology chrono = DateTimeUtils.getIntervalChronology(startInstant, endInstant); iType = type; iValues = chrono.get(this, startMillis, endMillis); } }
/** * Creates a period from the given start point and duration. * * @param startInstant the interval start, null means now * @param duration the duration of the interval, null means zero-length * @param type which set of fields this period supports, null means standard */ protected BasePeriod(ReadableInstant startInstant, ReadableDuration duration, PeriodType type) { super(); type = checkPeriodType(type); long startMillis = DateTimeUtils.getInstantMillis(startInstant); long durationMillis = DateTimeUtils.getDurationMillis(duration); long endMillis = FieldUtils.safeAdd(startMillis, durationMillis); Chronology chrono = DateTimeUtils.getInstantChronology(startInstant); iType = type; iValues = chrono.get(this, startMillis, endMillis); }
public DateTimeZone getZone() { Chronology base; if ((base = getBase()) != null) { return base.getZone(); } return DateTimeZone.UTC; }
/** * Parses a date-time from the given text, returning a new MutableDateTime. * <p> * The parse will use the zone and chronology specified on this formatter. * <p> * If the text contains a time zone string then that will be taken into * account in adjusting the time of day as follows. * If the {@link #withOffsetParsed()} has been called, then the resulting * DateTime will have a fixed offset based on the parsed time zone. * Otherwise the resulting DateTime will have the zone of this formatter, * but the parsed zone may have caused the time to be adjusted. * * @param text the text to parse, not null * @return the parsed date-time, never null * @throws UnsupportedOperationException if parsing is not supported * @throws IllegalArgumentException if the text to parse is invalid */ public MutableDateTime parseMutableDateTime(String text) { DateTimeParser parser = requireParser(); Chronology chrono = selectChronology(null); DateTimeParserBucket bucket = new DateTimeParserBucket(0, chrono, iLocale, iPivotYear, iDefaultYear); int newPos = parser.parseInto(bucket, text, 0); if (newPos >= 0) { if (newPos >= text.length()) { long millis = bucket.computeMillis(true, text); if (iOffsetParsed && bucket.getOffsetInteger() != null) { int parsedOffset = bucket.getOffsetInteger(); DateTimeZone parsedZone = DateTimeZone.forOffsetMillis(parsedOffset); chrono = chrono.withZone(parsedZone); } else if (bucket.getZone() != null) { chrono = chrono.withZone(bucket.getZone()); } MutableDateTime dt = new MutableDateTime(millis, chrono); if (iZone != null) { dt.setZone(iZone); } return dt; } } else { newPos = ~newPos; } throw new IllegalArgumentException(FormatUtils.createErrorMessage(text, newPos)); }
/** * Create a StrictChronology for any chronology. * * @param base the chronology to wrap * @throws IllegalArgumentException if chronology is null */ public static StrictChronology getInstance(Chronology base) { if (base == null) { throw new IllegalArgumentException("Must supply a chronology"); } return new StrictChronology(base); }
public long getDateTimeMillis(long instant, int hourOfDay, int minuteOfHour, int secondOfMinute, int millisOfSecond) throws IllegalArgumentException { Chronology base; if ((base = iBase) != null && (iBaseFlags & 1) == 1) { // Only call specialized implementation if applicable fields are the same. return base.getDateTimeMillis (instant, hourOfDay, minuteOfHour, secondOfMinute, millisOfSecond); } return super.getDateTimeMillis (instant, hourOfDay, minuteOfHour, secondOfMinute, millisOfSecond); }
/** * Serialization singleton */ private Object readResolve() { Chronology base = getBase(); int minDays = getMinimumDaysInFirstWeek(); minDays = (minDays == 0 ? 4 : minDays); // handle rename of BaseGJChronology return base == null ? getInstance(DateTimeZone.UTC, minDays) : getInstance(base.getZone(), minDays); }
/** * @param standardOffset standard offset just before previous recurrence */ public long previous(long instant, int standardOffset, int saveMillis) { int offset; if (iMode == 'w') { offset = standardOffset + saveMillis; } else if (iMode == 's') { offset = standardOffset; } else { offset = 0; } // Convert from UTC to local time. instant += offset; Chronology chrono = ISOChronology.getInstanceUTC(); long prev = chrono.monthOfYear().set(instant, iMonthOfYear); // Be lenient with millisOfDay. prev = chrono.millisOfDay().set(prev, 0); prev = chrono.millisOfDay().add(prev, iMillisOfDay); prev = setDayOfMonthPrevious(chrono, prev); if (iDayOfWeek == 0) { if (prev >= instant) { prev = chrono.year().add(prev, -1); prev = setDayOfMonthPrevious(chrono, prev); } } else { prev = setDayOfWeek(chrono, prev); if (prev >= instant) { prev = chrono.year().add(prev, -1); prev = chrono.monthOfYear().set(prev, iMonthOfYear); prev = setDayOfMonthPrevious(chrono, prev); prev = setDayOfWeek(chrono, prev); } } // Convert from local time to UTC. return prev - offset; }