Java Code Examples for org.joda.time.DateTime#withYear()

The following examples show how to use org.joda.time.DateTime#withYear() . These examples are extracted from open source projects. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
public void test_setYear() {
    Chronology zone = LenientChronology.getInstance(ISOChronology.getInstanceUTC());
    DateTime dt = new DateTime(2007, 1, 1, 0, 0 ,0, 0, zone);
    assertEquals("2007-01-01T00:00:00.000Z", dt.toString());
    dt = dt.withYear(2008);
    assertEquals("2008-01-01T00:00:00.000Z", dt.toString());
}
 
Example 2
public void test_setYear() {
    Chronology zone = LenientChronology.getInstance(ISOChronology.getInstanceUTC());
    DateTime dt = new DateTime(2007, 1, 1, 0, 0 ,0, 0, zone);
    assertEquals("2007-01-01T00:00:00.000Z", dt.toString());
    dt = dt.withYear(2008);
    assertEquals("2008-01-01T00:00:00.000Z", dt.toString());
}
 
Example 3
Source Project: mt-flume   File: SyslogParser.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * 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
 */
protected long parseRfc3164Time(String ts) {
  DateTime now = DateTime.now();
  int year = now.getYear();

  ts = TWO_SPACES.matcher(ts).replaceFirst(" ");

  DateTime date;
  try {
    date = rfc3164Format.parseDateTime(ts);
  } catch (IllegalArgumentException e) {
    logger.debug("rfc3164 date parse failed on ("+ts+"): invalid format", e);
    return 0;
  }

  // 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
  if (date != null) {
    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;
  }

  if (date == null) {
    return 0;
  }

  return date.getMillis();
}
 
Example 4
/**
 * This method returns the year of the current message. First it makes a clone of the current date.
 * Then we obtain the milliseconds for the current date and the last message's date and calculate 
 * the message time difference. Depending on the difference, return the year appropriately.
 * @param currentMessageDate the current date of the message.
 * @return the year of the message.
 */
public final int getDesiredYear(DateTime currentMessageDate) {
    int yearToReturn;
    DateTime curMessageDate = new DateTime(currentMessageDate);
    curMessageDate = curMessageDate.withYear(m_currentYear);
    if (m_lastSeenMessageDate == null) {
        m_lastSeenMessageDate = curMessageDate;
    }
    final long curDateMillis = curMessageDate.getMillis();
    final long lastDateMillis = m_lastSeenMessageDate.getMillis();
    final long messageTimeDiff = curDateMillis - lastDateMillis;

    if (messageTimeDiff < 0) {
        /* cur message timestamp < last message timestamp.  There are two cases: */
        if (Math.abs(messageTimeDiff) < DECREMENT_DAYS_ALLOWANCE_IN_MILLIS) {
            /* Case: Message time goes backwards (maybe by a few minutes).   
             * The year is set to current year. */
            yearToReturn = m_currentYear;
        } else {
            /* Case: Year N to Year N+1.  
             * - Message time goes from Year N to Year N+1 (e.g. actual situation is 12/31/2001 to 1/1/2002, 
             *   and our test will compare 12/31/2001 and 1/1/2001)
             */
            m_currentYear++;
            curMessageDate = curMessageDate.withYear(m_currentYear);
            yearToReturn = m_currentYear;
            m_lastSeenMessageDate = curMessageDate;
            final String msg = m_source + ": Year increase by 1, to " + m_currentYear;
            LinuxSyslog3164ParserBase.s_logger.info(msg);
        }
    } else {
        /* last message timestamp < cur message timestamp. There are two cases:
         */
        if (messageTimeDiff < INCREMENT_DAYS_LIMIT_IN_MILLIS) {
            /* Case: The log time is increasing normally. In case of a missing log, we allow a specific limit, 
             * such as 300 days. */
            yearToReturn = m_currentYear;
            m_lastSeenMessageDate = curMessageDate;
        } else {
            /* Case: Message time goes from Year N to Year N-1 (e.g. actual situation is 1/1/2002 to 
             * 12/31/2001, and out test will compare 1/1/2002 and 12/31/2002.)
             * In this case, we don't change the m_currentYear.
             */
            yearToReturn = m_currentYear - 1;
        }
    }
    return yearToReturn;
}
 
Example 5
/**
 * Retrieves the date parsed from the header of a log. Unless otherwise defined in the properties file,
 * we have to use some logic to figure out the year. After parsing the date, we need to correct the time-zone. 
 * Then we set the dateTime to the current year. Now we need to check the dateTime and see if it's after today.
 * The logic is as follows:
 *      - If Log time-stamp < End of day of today 
 *          (comparing Month, Day, Hour, Minutes, Seconds, with year missing), 
 *          assume it's this year.
 *      - If Log time-stamp > End of day of today 
 *          (comparing Month, Day, Hour, Minutes, Seconds, with year missing), 
 *          assume it's previous year.
 * 
 * The following restrictions will be made to customer for BulkLoad:
 *      - Cannot upload logs older than 11 months.
 *      - Cannot upload logs that are continuous for more than 11 months.
 * 
 * Note: END OF TODAY is purposely chosen instead of START OF TODAY in case a user bulk loads logs that 
 * belongs to today.  It's not possible/likely that a user would bulk load logs from last year of the 
 * same day with the restriction we specified above.
 * @param source the source name string value.
 * @param s the date and time string value.
 * @return Date object with date/time-stamp of the Linux log.
 */
@Override
public final Date toDate(String source, String s) {
    DateTime dt = null;
    for (DateTimeFormatter fmt : dt_formatters) {
        try {
            dt = fmt.parseDateTime(s);
            dt = dt.withZoneRetainFields(INPUT_TIME_ZONE);
            dt = dt.withZone(OUTPUT_TIME_ZONE);

            /* Year must be set after all the time is normalized to the timezone */
            dt = dt.withYear(curYear);

            if (s_linuxAdeExtProperties.isYearDefined()) {
                yearSetter = LinuxSyslogYearSetter.getYearSetter(source);

                /* If years is defined, then, use the defined year as a starting year */
                final int yearToUse = yearSetter.getDesiredYear(dt);
                dt = dt.withYear(yearToUse);
            } else if (dt.isAfter(END_OF_TODAY)) {
                /* Set DateTime to previous year */
                dt = dt.withYear(curYear - 1);
            } else {
                dt = dt.withYear(curYear);
            }

            /* AdeCore will take the Java Date object, and convert 
             * it to the output time-zone, then extract the hour. */
            return dt.toDate();
        } catch (IllegalArgumentException e) {
            /* This exception can occur normally when iterating
             * through the DateTimeFormatter objects. It is only 
             * an error worth noting when the dt object is not null.
             */
            if (dt != null) {
                s_logger.error("Invalid argument encountered.", e);
            }
        }
    }
    throw new IllegalArgumentException("Failed to parse date " + s);
}
 
Example 6
Source Project: herd   File: AbstractDaoTest.java    License: Apache License 2.0 4 votes vote down vote up
/**
 * Returns a random timestamp.
 */
public static DateTime getRandomDateTime()
{
    DateTime dt = new DateTime(new Random().nextLong()).withMillisOfSecond(0);
    return dt.withYear(2019);
}