Example usage for org.joda.time DateTime getYear

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

Introduction

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

Prototype

public int getYear() 

Source Link

Document

Get the year field value.

Usage

From source file:com.squarespace.template.plugins.PluginDateUtils.java

License:Apache License

/**
 * Takes a strftime()-compatible format string and outputs the properly formatted date.
 *//*w w w.  ja va2s.  c  o m*/
public static void formatDate(Locale locale, String fmt, long instant, String tzName, StringBuilder buf) {
    DateTimeZone zone = null;
    try {
        zone = DateTimeZone.forID(tzName);
    } catch (IllegalArgumentException e) {
        zone = DateTimeZone.getDefault();
    }
    DateTime date = new DateTime(instant, zone);
    int index = 0;
    int len = fmt.length();
    while (index < len) {
        char c1 = fmt.charAt(index);
        index++;
        if (c1 != '%' || index == len) {
            buf.append(c1);
            continue;
        }
        char c2 = fmt.charAt(index);
        switch (c2) {
        case 'A':
            buf.append(date.dayOfWeek().getAsText(locale));
            break;
        case 'a':
            buf.append(date.dayOfWeek().getAsShortText(locale));
            break;
        case 'B':
            buf.append(date.monthOfYear().getAsText(locale));
            break;
        case 'b':
            buf.append(date.monthOfYear().getAsShortText(locale));
            break;
        case 'C':
            leftPad(date.centuryOfEra().get(), '0', 2, buf);
            break;
        case 'c':
            formatAggregate(DateTimeAggregate.FULL, locale, date, buf);
            break;
        case 'D':
            formatAggregate(DateTimeAggregate.MMDDYY, locale, date, buf);
            break;
        case 'd':
            leftPad(date.dayOfMonth().get(), '0', 2, buf);
            break;
        case 'e':
            leftPad(date.dayOfMonth().get(), ' ', 2, buf);
            break;
        case 'F':
            formatAggregate(DateTimeAggregate.YYYYMMDD, locale, date, buf);
            break;
        case 'G':
            buf.append(date.year().get());
            break;
        case 'g':
            leftPad(date.yearOfCentury().get(), '0', 2, buf);
            break;
        case 'H':
            leftPad(date.hourOfDay().get(), '0', 2, buf);
            break;
        case 'h':
            buf.append(date.monthOfYear().getAsShortText(locale));
            break;
        case 'I':
            leftPad(date.get(DateTimeFieldType.clockhourOfHalfday()), '0', 2, buf);
            break;
        case 'j':
            leftPad(date.dayOfYear().get(), '0', 3, buf);
            break;
        case 'k':
            leftPad(date.get(DateTimeFieldType.clockhourOfDay()), ' ', 2, buf);
            break;
        case 'l':
            leftPad(date.get(DateTimeFieldType.clockhourOfHalfday()), ' ', 2, buf);
            break;
        case 'M':
            leftPad(date.minuteOfHour().get(), '0', 2, buf);
            break;
        case 'm':
            leftPad(date.monthOfYear().get(), '0', 2, buf);
            break;
        case 'n':
            buf.append('\n');
            break;
        case 'P':
            buf.append(date.get(DateTimeFieldType.halfdayOfDay()) == 0 ? "am" : "pm");
            break;
        case 'p':
            buf.append(date.get(DateTimeFieldType.halfdayOfDay()) == 0 ? "AM" : "PM");
            break;
        case 'R':
            formatAggregate(DateTimeAggregate.H240_M0, locale, date, buf);
            break;
        case 'S':
            leftPad(date.secondOfMinute().get(), '0', 2, buf);
            break;
        case 's':
            buf.append(instant / 1000);
            break;
        case 't':
            buf.append('\t');
            break;
        case 'T':
            // Equivalent of %H:%M:%S
            formatAggregate(DateTimeAggregate.H240_M0, locale, date, buf);
            buf.append(':');
            leftPad(date.secondOfMinute().get(), '0', 2, buf);
            break;

        case 'U':
            // TODO: fix week-of-year number
            leftPad(date.weekOfWeekyear().get(), '0', 2, buf);
            break;

        case 'u':
            buf.append(date.dayOfWeek().get());
            break;

        case 'V':
            // TODO: fix week-of-year number
            leftPad(date.weekOfWeekyear().get(), '0', 2, buf);
            break;

        case 'v':
            // Equivalent of %e-%b-%Y
            leftPad(date.dayOfMonth().get(), ' ', 2, buf);
            buf.append('-');
            buf.append(date.monthOfYear().getAsShortText());
            buf.append('-');
            buf.append(date.getYear());
            break;

        case 'W':
            // TODO: fix week-of-year number
            break;

        case 'w':
            buf.append(date.dayOfWeek().get());
            break;
        case 'X':
            formatAggregate(DateTimeAggregate.HHMMSSP, locale, date, buf);
            break;
        case 'x':
            formatAggregate(DateTimeAggregate.MMDDYYYY, locale, date, buf);
            break;
        case 'Y':
            buf.append(date.getYear());
            break;
        case 'y':
            leftPad(date.getYearOfCentury(), '0', 2, buf);
            break;

        case 'Z':
            // Note: Joda's nameKey happens to be the same as the shortName. Making
            // this change to workaround Joda https://github.com/JodaOrg/joda-time/issues/288
            buf.append(zone.getNameKey(date.getMillis()));
            break;

        case 'z':
            int offset = date.getZone().getOffset(instant) / 60000;
            int hours = (int) Math.floor(offset / 60);
            int minutes = (hours * 60) - offset;
            if (offset < 0) {
                buf.append('-');
            }
            leftPad(Math.abs(hours), '0', 2, buf);
            leftPad(Math.abs(minutes), '0', 2, buf);
            break;

        default:
            // no match, emit literals.
            buf.append(c1).append(c2);
        }
        index++;
    }
}

From source file:com.squarespace.template.plugins.PluginDateUtils.java

License:Apache License

private static void formatAggregate(DateTimeAggregate type, Locale locale, DateTime date, StringBuilder buf) {
    switch (type) {
    case FULL://from  www . j  ava  2s. co m
        buf.append(date.dayOfWeek().getAsShortText(locale));
        buf.append(' ');
        leftPad(date.dayOfMonth().get(), '0', 2, buf);
        buf.append(' ');
        buf.append(date.monthOfYear().getAsShortText(locale));
        buf.append(' ');
        buf.append(date.year().get());
        buf.append(' ');
        leftPad(date.get(DateTimeFieldType.clockhourOfHalfday()), '0', 2, buf);
        buf.append(':');
        leftPad(date.minuteOfHour().get(), '0', 2, buf);
        buf.append(':');
        leftPad(date.secondOfMinute().get(), '0', 2, buf);
        buf.append(' ');
        buf.append(date.get(DateTimeFieldType.halfdayOfDay()) == 0 ? "AM" : "PM");
        buf.append(' ');
        buf.append(date.getZone().getNameKey(date.getMillis()));
        break;

    case H240_M0:
        leftPad(date.get(DateTimeFieldType.clockhourOfDay()), '0', 2, buf);
        buf.append(':');
        leftPad(date.minuteOfHour().get(), '0', 2, buf);
        break;

    case HHMMSSP:
        leftPad(date.get(DateTimeFieldType.hourOfHalfday()), '0', 2, buf);
        buf.append(':');
        leftPad(date.getMinuteOfHour(), '0', 2, buf);
        buf.append(':');
        leftPad(date.getSecondOfMinute(), '0', 2, buf);
        buf.append(' ');
        buf.append(date.get(DateTimeFieldType.halfdayOfDay()) == 0 ? "AM" : "PM");
        break;

    case MMDDYY:
        leftPad(date.getMonthOfYear(), '0', 2, buf);
        buf.append('/');
        leftPad(date.dayOfMonth().get(), '0', 2, buf);
        buf.append('/');
        leftPad(date.yearOfCentury().get(), '0', 2, buf);
        break;

    case MMDDYYYY:
        leftPad(date.getMonthOfYear(), '0', 2, buf);
        buf.append('/');
        leftPad(date.dayOfMonth().get(), '0', 2, buf);
        buf.append('/');
        buf.append(date.getYear());
        break;

    case YYYYMMDD:
        buf.append(date.year().get());
        buf.append('-');
        leftPad(date.monthOfYear().get(), '0', 2, buf);
        buf.append('-');
        leftPad(date.dayOfMonth().get(), '0', 2, buf);
        break;

    default:
        break;
    }
}

From source file:com.squid.kraken.v4.core.analysis.engine.processor.AnalysisCompute.java

License:Open Source License

private IntervalleObject alignPastInterval(IntervalleObject presentInterval, IntervalleObject pastInterval,
        Axis joinAxis) throws ScopeException {

    if (joinAxis != null && presentInterval != null && pastInterval != null) {

        Object lowerPresent = presentInterval.getLowerBound();
        Object lowerPast = pastInterval.getLowerBound();
        Object upperPresent = presentInterval.getUpperBound();
        Object upperPast = pastInterval.getUpperBound();
        ///*from w  ww . j  a v a2  s .co  m*/
        IDomain image = joinAxis.getDefinition().getImageDomain();
        if (lowerPresent instanceof Date && lowerPast instanceof Date) {

            DateTime lowerPastDT = new DateTime((Date) lowerPast);
            DateTime lowerPresentDT = new DateTime((Date) lowerPresent);
            DateTime upperPresentDT = new DateTime((Date) upperPresent);
            DateTime upperPastDT = new DateTime((Date) upperPast);

            // realign
            if (image.isInstanceOf(IDomain.YEARLY)) {
                // check if present is an exact number of years
                if (lowerPresentDT.getDayOfYear() == 1
                        && upperPresentDT.getDayOfYear() == upperPresentDT.dayOfYear().getMaximumValue()) {
                    // check of both periods have the same number of days
                    Period presentPeriod = new Period(new LocalDate(lowerPresent),
                            (new LocalDate(upperPresent)), PeriodType.days());
                    Period pastPeriod = new Period(new LocalDate(lowerPast), (new LocalDate(upperPast)),
                            PeriodType.days());
                    if (presentPeriod.getDays() == pastPeriod.getDays()) {
                        presentPeriod = new Period(new LocalDate(lowerPresent),
                                (new LocalDate(upperPresent)).plusDays(1), PeriodType.years());
                        pastPeriod = new Period(new LocalDate(lowerPast),
                                (new LocalDate(upperPast)).plusDays(1), PeriodType.years());

                        // realign
                        if (presentPeriod.getYears() > pastPeriod.getYears()) {
                            // some days are missing to align the periods
                            if (lowerPastDT.getDayOfYear() != 1) {
                                // previous period
                                Date newLowerPast = new DateTime(upperPastDT.getYear(), 1, 1, 0, 0).toDate();
                                return new IntervalleObject(newLowerPast, upperPast);
                            }
                            if (upperPastDT.getDayOfYear() != upperPastDT.dayOfYear().getMaximumValue()) {
                                // year over year
                                Date newUpperPast = new DateTime(upperPastDT.getYear(), 12, 31, 23, 59)
                                        .toDate();
                                return new IntervalleObject(lowerPast, newUpperPast);
                            }
                        } else {
                            // either already aligned, or some days should
                            // be removed

                            if (upperPastDT.getDayOfYear() != upperPastDT.dayOfYear().getMaximumValue()) {
                                // year over Year
                                Date newUpperPast = new DateTime(upperPastDT.getYear() - 1, 12, 31, 23, 59)
                                        .toDate();
                                return new IntervalleObject(lowerPast, newUpperPast);

                            }
                            if (lowerPastDT.getDayOfYear() != 1) {
                                // previous period
                                Date newLowerPast = new DateTime(lowerPastDT.getYear() + 1, 1, 1, 0, 0)
                                        .toDate();
                                return new IntervalleObject(newLowerPast, upperPast);
                            }

                        }
                    }
                }
            } else if (image.isInstanceOf(IDomain.QUATERLY) || image.isInstanceOf(IDomain.MONTHLY)) {
                // check if present is an exact number of month
                if (lowerPresentDT.getDayOfMonth() == 1
                        && upperPresentDT.getDayOfMonth() == upperPresentDT.dayOfMonth().getMaximumValue()) {
                    // check of both periods have the same number of days
                    Period presentPeriod = new Period(new LocalDate(lowerPresent), new LocalDate(upperPresent),
                            PeriodType.days());
                    Period pastPeriod = new Period(new LocalDate(lowerPast), new LocalDate(upperPast),
                            PeriodType.days());
                    if (presentPeriod.getDays() == pastPeriod.getDays()) {
                        // realign
                        presentPeriod = new Period(new LocalDate(lowerPresent),
                                (new LocalDate(upperPresent)).plusDays(1), PeriodType.months());
                        pastPeriod = new Period(new LocalDate(lowerPast),
                                (new LocalDate(upperPast)).plusDays(1), PeriodType.months());
                        if (presentPeriod.getMonths() > pastPeriod.getMonths()) {
                            // some days are missing

                            if (upperPastDT.getDayOfMonth() != upperPastDT.dayOfMonth().getMaximumValue()) {
                                // month over month
                                Date newUpperPast = new DateTime(upperPastDT.getYear(),
                                        upperPastDT.getMonthOfYear(),
                                        upperPastDT.dayOfMonth().getMaximumValue(), 23, 59).toDate();
                                return new IntervalleObject(lowerPast, newUpperPast);
                            }

                            if (lowerPastDT.getDayOfMonth() != 1) {
                                // previous period
                                Date newLowerPast = new DateTime(lowerPastDT.getYear(),
                                        lowerPastDT.getMonthOfYear(), 1, 0, 0).toDate();
                                return new IntervalleObject(newLowerPast, upperPast);

                            }

                        } else {
                            // either already aligned, of some days should
                            // be removed
                            if (upperPastDT.getDayOfMonth() != upperPastDT.dayOfMonth().getMaximumValue()) {
                                /// month over month
                                if (upperPastDT.getMonthOfYear() == 1) {
                                    Date newUpperPast = new DateTime(upperPastDT.getYear() - 1, 12, 31, 23, 59)
                                            .toDate();
                                    return new IntervalleObject(lowerPast, newUpperPast);

                                } else {

                                    upperPastDT = upperPastDT.minusMonths(1);
                                    Date newUpperPast = new DateTime(upperPastDT.getYear(),
                                            upperPastDT.getMonthOfYear(),
                                            upperPastDT.dayOfMonth().getMaximumValue(), 23, 59).toDate();
                                    return new IntervalleObject(lowerPast, newUpperPast);
                                }
                            }
                            if (lowerPastDT.getDayOfMonth() != 1) {
                                // previous period
                                if (lowerPastDT.getMonthOfYear() == 12) {
                                    Date newLowerPast = new DateTime(lowerPastDT.getYear() + 1, 1, 1, 0, 0)
                                            .toDate();
                                    return new IntervalleObject(newLowerPast, upperPast);

                                } else {
                                    lowerPastDT = lowerPastDT.plusMonths(1);
                                    Date newLowerPast = new DateTime(lowerPastDT.getYear(),
                                            lowerPastDT.getMonthOfYear(), 1, 0, 0).toDate();
                                    return new IntervalleObject(newLowerPast, upperPast);

                                }

                            }

                        }
                    }
                }
            }
        }
    }
    return pastInterval;
}

From source file:com.squid.kraken.v4.core.analysis.engine.processor.AnalysisCompute.java

License:Open Source License

private Period computeOffset(IntervalleObject presentInterval, IntervalleObject pastInterval,
        AxisValues joinAxis) throws ScopeException {
    // it is better to compare on the lower bound because alignment on the
    // end of month is not accurate
    Object present = presentInterval.getLowerBound();
    Object past = pastInterval.getLowerBound();
    ////from  w w  w .j  a  va  2  s  .c  o m

    IDomain image = joinAxis.getAxis().getDefinition().getImageDomain();
    PeriodType type = computePeriodType(image);
    //
    if (present instanceof Date && past instanceof Date) {

        Period presentPeriod = new Period(new LocalDate(((Date) presentInterval.getLowerBound()).getTime()),
                new LocalDate(((Date) presentInterval.getUpperBound()).getTime()).plusDays(1), type);

        Period pastPeriod = new Period(new LocalDate(((Date) pastInterval.getLowerBound()).getTime()),
                new LocalDate(((Date) pastInterval.getUpperBound()).getTime()).plusDays(1), type);

        Date pastDate = (Date) past;
        DateTime dt = new DateTime(pastDate);
        if (image.isInstanceOf(IDomain.YEARLY)) {
            if (presentPeriod.getYears() > pastPeriod.getYears()) {
                // e.g. presentPeriod of 365 days ->
                // presentPeriod.getYears=1 && past year of 366 days ->
                // pastPeriod.getYears=0
                DateTime newDT = new DateTime(dt.getYear(), 1, 1, 0, 0);
                pastDate = newDT.toDate();
            } else {
                if (dt.getDayOfYear() != 1) {
                    // e.g present period of 366 days -> past date at dec 31
                    DateTime newDT = new DateTime(dt.getYear() + 1, 1, 1, 0, 0);
                    pastDate = newDT.toDate();
                }
            }
        } else if (image.isInstanceOf(IDomain.QUATERLY) || image.isInstanceOf(IDomain.MONTHLY)) {

            if (presentPeriod.getMonths() > pastPeriod.getMonths()) {
                // e.g present period of 28 days(February) ->
                // pastPeriod.getMonths() = 0 (January has 31 days)
                DateTime newDT = new DateTime(dt.getYear(), dt.getMonthOfYear(), 1, 0, 0);
                pastDate = newDT.toDate();
            } else {
                if (dt.getDayOfMonth() != 1) {
                    // e.g. present period of 31 day(March) pastDate = Feb 6
                    if (dt.getMonthOfYear() == 12) {
                        DateTime newDT = new DateTime(dt.getYear() + 1, 1, 1, 0, 0);
                        pastDate = newDT.toDate();
                    } else {
                        DateTime newDT = new DateTime(dt.getYear(), dt.getMonthOfYear() + 1, 1, 0, 0);
                        pastDate = newDT.toDate();
                    }
                }
            }
        } else {
            // daily, keep Date as it is
        }
        return new Period(new LocalDate((pastDate).getTime()), new LocalDate(((Date) present).getTime()), type);

    } else {
        return null;
    }
}

From source file:com.streamsets.pipeline.lib.parser.syslog.SyslogParser.java

License:Apache License

/**
 * Parse the RFC3164 date format. This is trickier than it sounds because this
 * format does not specify a year so we get weird edge cases at year
 * boundaries. This implementation tries to "do what I mean".
 * @param ts RFC3164-compatible timestamp to be parsed
 * @return Typical (for Java) milliseconds since the UNIX epoch
 *//*from  w ww .  j a  va 2s .  c o m*/
protected long parseRfc3164Time(String ts) throws OnRecordErrorException {
    DateTime now = DateTime.now();
    int year = now.getYear();
    ts = TWO_SPACES.matcher(ts).replaceFirst(" ");
    DateTime date;
    try {
        date = rfc3164Format.parseDateTime(ts);
    } catch (IllegalArgumentException e) {
        throw new OnRecordErrorException(Errors.SYSLOG_10, ts, e);
    }
    // try to deal with boundary cases, i.e. new year's eve.
    // rfc3164 dates are really dumb.
    // NB: cannot handle replaying of old logs or going back to the future
    DateTime fixed = date.withYear(year);
    // flume clock is ahead or there is some latency, and the year rolled
    if (fixed.isAfter(now) && fixed.minusMonths(1).isAfter(now)) {
        fixed = date.withYear(year - 1);
        // flume clock is behind and the year rolled
    } else if (fixed.isBefore(now) && fixed.plusMonths(1).isBefore(now)) {
        fixed = date.withYear(year + 1);
    }
    date = fixed;
    return date.getMillis();
}

From source file:com.streamsets.pipeline.lib.parser.udp.syslog.SyslogParser.java

License:Apache License

/**
 * Parse the RFC3164 date format. This is trickier than it sounds because this
 * format does not specify a year so we get weird edge cases at year
 * boundaries. This implementation tries to "do what I mean".
 * @param ts RFC3164-compatible timestamp to be parsed
 * @return Typical (for Java) milliseconds since the UNIX epoch
 */// w w  w  . j  a va2s .  c  o m
protected long parseRfc3164Time(String recordIdentifer, String msg, String ts) throws OnRecordErrorException {
    DateTime now = DateTime.now();
    int year = now.getYear();
    ts = TWO_SPACES.matcher(ts).replaceFirst(" ");
    DateTime date;
    try {
        date = rfc3164Format.parseDateTime(ts);
    } catch (IllegalArgumentException e) {
        throw throwOnRecordErrorException(recordIdentifer, msg, Errors.SYSLOG_10, ts, e);
    }
    // try to deal with boundary cases, i.e. new year's eve.
    // rfc3164 dates are really dumb.
    // NB: cannot handle replaying of old logs or going back to the future
    DateTime fixed = date.withYear(year);
    // flume clock is ahead or there is some latency, and the year rolled
    if (fixed.isAfter(now) && fixed.minusMonths(1).isAfter(now)) {
        fixed = date.withYear(year - 1);
        // flume clock is behind and the year rolled
    } else if (fixed.isBefore(now) && fixed.plusMonths(1).isBefore(now)) {
        fixed = date.withYear(year + 1);
    }
    date = fixed;
    return date.getMillis();
}

From source file:com.tech.auju.display.Gudang.java

private void generate() {
    //        int d1 = (int) spDay1.getValue();
    //        int d2 = (int) spDay2.getValue();
    //        int m1 = cbMonth1.getSelectedIndex() + 1;
    //        int m2 = cbMonth2.getSelectedIndex() + 1;
    //        //1900
    //        int y1 = (int) spYear1.getValue();
    //        int y2 = (int) spYear2.getValue();

    DateTime dt = new DateTime();
    int y = dt.getYear() - 1900;
    int m = dt.monthOfYear().get() - 1;
    int d = dt.dayOfMonth().get();

    Date date1 = new Date(y, m, d);
    Date date2 = new Date(y, m, d);

    try {// w  ww.j av a 2  s  .  c  o m
        new DocumentMaker().printArsip(date1, date2);
    } catch (FileNotFoundException ex) {
        Logger.getLogger(DocGenerator.class.getName()).log(Level.SEVERE, null, ex);
    } catch (JRException ex) {
        Logger.getLogger(DocGenerator.class.getName()).log(Level.SEVERE, null, ex);
    }
    System.out.println("1. " + date1.getDay() + date1.getMonth() + date1.getYear());
    //        System.out.println("2. " + d2 + m2 + y2);
}

From source file:com.tech.auju.implementation.GudangImpl.java

/**
 * Get today date./* ww  w .ja  va  2 s .c  om*/
 * @return Today date.
 */
private Date getTime() {
    DateTime dt = new DateTime();
    int d = dt.getDayOfMonth();
    int m = dt.getMonthOfYear();
    int y = dt.getYear();
    System.out.println("GETTIME : " + y + m + d);
    return new Date(y - 1900, m, d);
}

From source file:com.tech.auju.implementation.PembelianImpl.java

/**
 * Get today date.//  w w  w .  jav a 2s.  c  o  m
 * @return Today date.
 */
private Date getTime() {
    DateTime dt = new DateTime();
    int d = dt.getDayOfWeek();
    int m = dt.getMonthOfYear();
    int y = dt.getYear();

    return new Date(y - 1900, m, d);
}

From source file:com.thinkbiganalytics.metadata.jpa.jobrepo.job.JpaBatchJobExecution.java

License:Apache License

@Override
public void setStartTime(DateTime startTime) {
    this.startTime = startTime;
    if (startTime != null) {
        this.startYear = startTime.getYear();
        this.startMonth = startTime.getMonthOfYear();
        this.startDay = startTime.getDayOfMonth();
    }/* w w w.ja  va2 s.co m*/
}