SyslogUtils { public static long parseTimestampToEpochMillis(String logTimestamp, Clock deviceClock) throws ParseException { ZoneId deviceTimeZone = deviceClock.getZone(); if (Pattern.matches("[A-Z][a-z]{2}(?:(?:\\s{2}\\d)|(?:\\s\\d{2}))\\s\\d{2}:\\d{2}:\\d{2}", logTimestamp)) { DateTimeFormatter inputFormat = DateTimeFormatter.ofPattern("MMM ppd HH:mm:ss").withZone(deviceTimeZone); TemporalAccessor inputDate = inputFormat.parse(logTimestamp); int inputMonth = inputDate.get(MONTH_OF_YEAR); int inputDay = inputDate.get(DAY_OF_MONTH); int inputHour = inputDate.get(HOUR_OF_DAY); int inputMinute = inputDate.get(MINUTE_OF_HOUR); int inputSecond = inputDate.get(SECOND_OF_MINUTE); ZonedDateTime currentDate = ZonedDateTime.now(deviceClock); int currentYear = currentDate.getYear(); ZonedDateTime inputDateWithCurrentYear = ZonedDateTime.of(currentYear, inputMonth, inputDay, inputHour, inputMinute, inputSecond, 0, deviceTimeZone); if(inputDateWithCurrentYear.isAfter(currentDate.plusDays(4L))) { ZonedDateTime inputDateWithPreviousYear = ZonedDateTime.of(currentYear-1, inputMonth, inputDay, inputHour, inputMinute, inputSecond, 0, deviceTimeZone); return inputDateWithPreviousYear.toInstant().toEpochMilli(); } else return inputDateWithCurrentYear.toInstant().toEpochMilli(); } else if (Pattern.matches("[A-Z][a-z]{2}\\s\\d{2}\\s\\d{4}\\s\\d{2}:\\d{2}:\\d{2}", logTimestamp)) return convertToEpochMillis(logTimestamp, DateTimeFormatter.ofPattern("MMM dd yyyy HH:mm:ss").withZone(deviceTimeZone)); else if (Pattern.matches("\\d{4}-\\d{2}-\\d{2}T\\d{2}:\\d{2}:\\d{2}(?:\\.\\d+)?(?:Z|[+-]\\d{2}:\\d{2})", logTimestamp)) return convertToEpochMillis(logTimestamp, DateTimeFormatter.ISO_OFFSET_DATE_TIME); else throw new ParseException(String.format("Unsupported date format: '%s'", logTimestamp)); }  static long parseTimestampToEpochMillis(String logTimestamp, Clock deviceClock); static String getSeverityFromPriority(int priority); static String getFacilityFromPriority(int priority);  }
@Test public void testRfc3164Timestamp() throws ParseException { String originalTimestamp = "Oct 9 13:42:11"; ZonedDateTime fixedInstant = ZonedDateTime.of(2016, 10, 8, 18, 30, 30, 0, ZoneOffset.UTC); Clock fixedClock = Clock.fixed(fixedInstant.toInstant(), fixedInstant.getZone()); assertEquals(SyslogUtils.parseTimestampToEpochMillis(originalTimestamp, fixedClock), 1476020531000L); }
@Test public void testRfc3164TimestampBackDate() throws ParseException { String originalTimestamp = "Oct 9 13:42:11"; ZonedDateTime fixedInstant = ZonedDateTime.of(2016, 10, 1, 18, 30, 30, 0, ZoneOffset.UTC); Clock fixedClock = Clock.fixed(fixedInstant.toInstant(), fixedInstant.getZone()); assertEquals(SyslogUtils.parseTimestampToEpochMillis(originalTimestamp, fixedClock), 1444398131000L); }