Java Code Examples for org.joda.time.format.DateTimeFormatter#parseDateTime()

The following examples show how to use org.joda.time.format.DateTimeFormatter#parseDateTime() . 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
Source File: DateFormatterTest.java    From twiliochat-android with MIT License 6 votes vote down vote up
@Test
public void testGetDateFromISOString() {
    String inputDate = "2015-10-21T07:28:00.000Z";

    DateTimeFormatter isoFormatter = ISODateTimeFormat.dateTime();
    DateTime date = null;

    try {
        date = isoFormatter.parseDateTime(inputDate);
    } catch (IllegalArgumentException e) {
        e.printStackTrace();
    }

    DateTime outputDate = DateFormatter.getDateFromISOString(inputDate);

    assertEquals(outputDate, date);
}
 
Example 2
Source File: BitbucketManager.java    From scava with Eclipse Public License 2.0 5 votes vote down vote up
public static java.util.Date convertStringToDate(String isoDate) {

		isoDate = isoDate.replaceAll("\"", "");
		DateTimeFormatter parser = ISODateTimeFormat.dateTimeParser();
		DateTime date = parser.parseDateTime(isoDate);
		return date.toDate();
	}
 
Example 3
Source File: TimeUtils.java    From anno4j with Apache License 2.0 5 votes vote down vote up
private static boolean testMillisFormat(String time) {
    DateTimeFormatter formatWithMillis = ISODateTimeFormat.dateTime().withZoneUTC();

    try {
        formatWithMillis.parseDateTime(time);
        return true;
    }  catch (IllegalArgumentException e) {
        return false;
    }
}
 
Example 4
Source File: HoraireComparator.java    From ETSMobile-Android2 with Apache License 2.0 5 votes vote down vote up
@Override
public int compare(IHoraireRows lhs, IHoraireRows rhs) {
    DateTimeFormatter formatter = null;
    DateTime eventDay1 = null;
    DateTime eventDay2 = null;

    if(lhs.getClass().equals(Event.class)){
        formatter = DateTimeFormat.forPattern("yyyy-MM-dd'T'HH:mm:ss'Z'");
        eventDay1 = formatter.parseDateTime(lhs.getDateDebut());
    }
    if(rhs.getClass().equals(Event.class)){
        formatter = DateTimeFormat.forPattern("yyyy-MM-dd'T'HH:mm:ss'Z'");
        eventDay2 = formatter.parseDateTime(rhs.getDateDebut());
    }

    if (lhs.getClass().equals(Seances.class)){
        formatter = DateTimeFormat.forPattern("yyyy-MM-dd'T'HH:mm:ss");
        eventDay1 = formatter.parseDateTime(lhs.getDateDebut());
    }
    if (rhs.getClass().equals(Seances.class)){
        formatter = DateTimeFormat.forPattern("yyyy-MM-dd'T'HH:mm:ss");
        eventDay2 = formatter.parseDateTime(rhs.getDateDebut());
    }

    if (eventDay1.isAfter(eventDay2)) {
        return 1;
    }
    else if(eventDay1.isBefore(eventDay2)){
        return -1;
    }
    else if(eventDay1.isEqual(eventDay2)){
        return 0;
    }
    return 0;
}
 
Example 5
Source File: DateTimeTypeAdapter.java    From devicehive-java with Apache License 2.0 5 votes vote down vote up
@Override
public DateTime deserialize(JsonElement json, Type typeOfT, JsonDeserializationContext context) throws JsonParseException {

    if (json.getAsString() == null || json.getAsString().isEmpty()) {
        return null;
    }

    final DateTimeFormatter formatter = DateTimeFormat.forPattern(iso_pattern).withZoneUTC();
    return formatter.parseDateTime(json.getAsString());
}
 
Example 6
Source File: TimeUtils.java    From anno4j with Apache License 2.0 5 votes vote down vote up
private static boolean testNoMillisFormat(String time) {
    DateTimeFormatter formatNoMillis = ISODateTimeFormat.dateTimeNoMillis().withZoneUTC();

    try {
        formatNoMillis.parseDateTime(time);
        return true;
    }  catch (IllegalArgumentException e) {
        return false;
    }
}
 
Example 7
Source File: BitbucketIssue.java    From scava with Eclipse Public License 2.0 5 votes vote down vote up
public static Date convertStringToDate(String isoDate) {

		isoDate = isoDate.replaceAll("\"", "");
		DateTimeFormatter parser = ISODateTimeFormat.dateTimeParser();
		DateTime date = parser.parseDateTime(isoDate);
		return date.toDate();
	}
 
Example 8
Source File: RuleGeneratorTest.java    From phoenix with Apache License 2.0 5 votes vote down vote up
/**
 * Asserts that the value field is between the min/max value fields
 *
 * @param value
 */
private void assertDateBetween(DataValue value) {
    DateTimeFormatter fmtr = DateTimeFormat.forPattern(PherfConstants.DEFAULT_DATE_PATTERN).withZone(DateTimeZone.UTC);

    DateTime dt = fmtr.parseDateTime(value.getValue());
    DateTime min = fmtr.parseDateTime(value.getMinValue());
    DateTime max = fmtr.parseDateTime(value.getMaxValue());

    assertTrue("Value " + dt + " is not after minValue", dt.isAfter(min));
    assertTrue("Value " + dt + " is not before maxValue", dt.isBefore(max));
}
 
Example 9
Source File: StreamsDateTimeDeserializer.java    From streams with Apache License 2.0 5 votes vote down vote up
/**
 * Applies each additional format in turn, until it can provide a non-null DateTime
 */
@Override
public DateTime deserialize(JsonParser jpar, DeserializationContext context) throws IOException {

  DateTime result = RFC3339Utils.parseToUTC(jpar.getValueAsString());
  Iterator<DateTimeFormatter> iterator = formatters.iterator();
  while ( result == null && iterator.hasNext()) {
    DateTimeFormatter formatter = iterator.next();
    result = formatter.parseDateTime(jpar.getValueAsString());
  }
  return result;
}
 
Example 10
Source File: DateTimeParameter.java    From ipst with Mozilla Public License 2.0 5 votes vote down vote up
public DateTimeParameter(String dateTime) throws Exception {
    Objects.requireNonNull(dateTime);
    DateTimeFormatter fmt = ISODateTimeFormat.dateTime();
    try {
        this.dateTime = fmt.parseDateTime(dateTime);
    } catch (IllegalArgumentException ex) {
        throw new WebApplicationException(Response.status(Status.BAD_REQUEST)
                .entity("Wrong date parameter format: " + ex.getMessage()).build());
    }
}
 
Example 11
Source File: TypeUtilsBak.java    From MeteoInfo with GNU Lesser General Public License v3.0 5 votes vote down vote up
/**
 * Returns the first DateTimeFormatter to parse the string, which represents a TIME
 * <p>
 * It's intended to be called at the start of a large formatting job so that it picks the write format and is not
 * called again. This is an optimization, because the older version, which will try multiple formatters was too
 * slow for large data sets.
 */
public static DateTimeFormatter getTimeFormatter(String timeValue) {
    for (DateTimeFormatter formatter : timeFormatters) {
        try {
            formatter.parseDateTime(timeValue);
            return formatter;
        } catch (DateTimeParseException e) {
            // ignore;
        }
    }
    return DATE_FORMATTER;
}
 
Example 12
Source File: HibernateMetadataVersionStoreTest.java    From dhis2-core with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
@Test
public void testGetAllVersionsInBetween() throws Exception
{
    DateTimeFormatter dateTimeFormatter = DateTimeFormat.forPattern( "yyyy-MM-dd HH:mm:ssZ" );
    org.joda.time.DateTime dateTime1 = dateTimeFormatter.parseDateTime( "2016-06-20 10:45:50Z" );
    org.joda.time.DateTime dateTime2 = dateTimeFormatter.parseDateTime( "2016-06-21 10:45:50Z" );
    org.joda.time.DateTime dateTime3 = dateTimeFormatter.parseDateTime( "2016-06-22 10:45:50Z" );

    assertEquals( 0, metadataVersionStore.getAllVersionsInBetween( new Date(), new Date() ).size() );

    MetadataVersion metadataVersion2 = new MetadataVersion( "version2", VersionType.ATOMIC );
    metadataVersion2.setHashCode( "12222" );
    metadataVersion2.setCreated( dateTime1.toDate() );
    metadataVersionStore.save( metadataVersion2 );

    MetadataVersion metadataVersion3 = new MetadataVersion( "version3", VersionType.ATOMIC );
    metadataVersion3.setHashCode( "12255" );
    metadataVersion3.setCreated( dateTime2.toDate() );
    metadataVersionStore.save( metadataVersion3 );

    MetadataVersion metadataVersion4 = new MetadataVersion( "version4", VersionType.ATOMIC );
    metadataVersion4.setHashCode( "12267" );
    metadataVersion4.setCreated( dateTime3.toDate() );
    metadataVersionStore.save( metadataVersion4 );

    List<MetadataVersion> allVersionsInBetween = metadataVersionStore.getAllVersionsInBetween( dateTime1.toDate(), dateTime2.toDate() );

    assertEquals( 2, allVersionsInBetween.size() );
    assertEquals( metadataVersion2, allVersionsInBetween.get( 0 ) );
    assertEquals( metadataVersion3, allVersionsInBetween.get( 1 ) );
    assertEquals( 0, metadataVersionStore.getAllVersionsInBetween( new Date(), new Date() ).size() );

    metadataVersionStore.delete( metadataVersion2 );
    metadataVersionStore.delete( metadataVersion3 );
    metadataVersionStore.delete( metadataVersion4 );
}
 
Example 13
Source File: TypeUtilsBak.java    From MeteoInfo with GNU Lesser General Public License v3.0 5 votes vote down vote up
/**
 * Returns the first DateTimeFormatter to parse the string, which represents a DATE
 * <p>
 * It's intended to be called at the start of a large formatting job so that it picks the write format and is not
 * called again. This is an optimization, because the older version, which will try multiple formatters was too
 * slow for large data sets.
 */
public static DateTimeFormatter getDateFormatter(String dateValue) {

    for (DateTimeFormatter formatter : dateFormatters) {
        try {
            formatter.parseDateTime(dateValue);
            return formatter;
        } catch (DateTimeParseException e) {
            // ignore;
        }
    }
    return DATE_FORMATTER;
}
 
Example 14
Source File: GitLabManager.java    From scava with Eclipse Public License 2.0 5 votes vote down vote up
public static java.util.Date convertStringToDate(String isoDate) {
	
	isoDate = isoDate.replaceAll("\"", "");
	DateTimeFormatter parser = ISODateTimeFormat.dateTimeParser();
	DateTime date = parser.parseDateTime(isoDate);
	return date.toDate();
}
 
Example 15
Source File: LinuxSyslog3164ParserBase.java    From ade with GNU General Public License v3.0 4 votes vote down vote up
/**
 * 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 16
Source File: DateTimeUtil.java    From DrivingAgency with MIT License 4 votes vote down vote up
public static Date strToDate(String dateTimeStr){
    DateTimeFormatter dateTimeFormatter = DateTimeFormat.forPattern(STANDARD_FORMAT);
    DateTime dateTime = dateTimeFormatter.parseDateTime(dateTimeStr);
    return dateTime.toDate();
}
 
Example 17
Source File: DateTimeUtil.java    From DrivingAgency with MIT License 4 votes vote down vote up
public static Date strToDate(String dateTimeStr, String formatStr){
    DateTimeFormatter dateTimeFormatter = DateTimeFormat.forPattern(formatStr);
    DateTime dateTime = dateTimeFormatter.parseDateTime(dateTimeStr);
    return dateTime.toDate();
}
 
Example 18
Source File: DateTimeUtil.java    From mmall-kay-Java with Apache License 2.0 4 votes vote down vote up
public static Date strToDate(String dateStr, String formatStr) {
    DateTimeFormatter dateTimeFormatter = DateTimeFormat.forPattern(formatStr);
    DateTime dateTime = dateTimeFormatter.parseDateTime(dateStr);
    return dateTime.toDate();
}
 
Example 19
Source File: TestDetectionJobSchedulerUtils.java    From incubator-pinot with Apache License 2.0 4 votes vote down vote up
@Test
public void testGetNewEntriesForDetectionSchedulerDaily() throws Exception {

  DatasetConfigDTO datasetConfig = new DatasetConfigDTO();
  datasetConfig.setTimeColumn("Date");
  datasetConfig.setTimeUnit(TimeUnit.DAYS);
  datasetConfig.setTimeDuration(1);
  DateTimeZone dateTimeZone = DateTimeZone.UTC;

  AnomalyFunctionDTO anomalyFunction = new AnomalyFunctionDTO();

  DateTimeFormatter dateTimeFormatter = DetectionJobSchedulerUtils.
      getDateTimeFormatterForDataset(datasetConfig, dateTimeZone);
  String currentDateTimeString = "201702140337";
  String currentDateTimeStringRounded = "20170214";
  DateTime currentDateTime = minuteDateTimeFormatter.parseDateTime(currentDateTimeString);
  DateTime currentDateTimeRounded = dateTimeFormatter.parseDateTime(currentDateTimeStringRounded);
  DetectionStatusDTO lastEntryForFunction = null;

  // null last entry
  Map<String, Long> newEntries = DetectionJobSchedulerUtils.
      getNewEntries(currentDateTime, lastEntryForFunction, anomalyFunction, datasetConfig, dateTimeZone);
  Assert.assertEquals(newEntries.size(), 1);
  Assert.assertEquals(newEntries.get(currentDateTimeStringRounded), new Long(currentDateTimeRounded.getMillis()));

  // last entry same as current time
  lastEntryForFunction = new DetectionStatusDTO();
  lastEntryForFunction.setDateToCheckInSDF(currentDateTimeStringRounded);
  lastEntryForFunction.setDateToCheckInMS(currentDateTimeRounded.getMillis());

  newEntries = DetectionJobSchedulerUtils.
      getNewEntries(currentDateTime, lastEntryForFunction, anomalyFunction, datasetConfig, dateTimeZone);
  Assert.assertEquals(newEntries.size(), 0);

  // last entry 1 day before current time
  String lastEntryDateTimeString = "20170213";
  DateTime lastEntryDateTime = dateTimeFormatter.parseDateTime(lastEntryDateTimeString);
  lastEntryForFunction = new DetectionStatusDTO();
  lastEntryForFunction.setDateToCheckInSDF(lastEntryDateTimeString);
  lastEntryForFunction.setDateToCheckInMS(lastEntryDateTime.getMillis());

  newEntries = DetectionJobSchedulerUtils.
      getNewEntries(currentDateTime, lastEntryForFunction, anomalyFunction, datasetConfig, dateTimeZone);
  Assert.assertEquals(newEntries.size(), 1);
  Assert.assertEquals(newEntries.get(currentDateTimeStringRounded), new Long(currentDateTimeRounded.getMillis()));

  // last entry 3 days before current time
  lastEntryDateTimeString = "20170211";
  lastEntryDateTime = dateTimeFormatter.parseDateTime(lastEntryDateTimeString);
  lastEntryForFunction = new DetectionStatusDTO();
  lastEntryForFunction.setDateToCheckInSDF(lastEntryDateTimeString);
  lastEntryForFunction.setDateToCheckInMS(lastEntryDateTime.getMillis());

  newEntries = DetectionJobSchedulerUtils.
      getNewEntries(currentDateTime, lastEntryForFunction, anomalyFunction, datasetConfig, dateTimeZone);
  Assert.assertEquals(newEntries.size(), 3);
  Assert.assertNotNull(newEntries.get("20170212"));
  Assert.assertNotNull(newEntries.get("20170213"));
  Assert.assertNotNull(newEntries.get("20170214"));
  Assert.assertEquals(newEntries.get(currentDateTimeStringRounded), new Long(currentDateTimeRounded.getMillis()));
}
 
Example 20
Source File: RulesApplier.java    From phoenix with Apache License 2.0 4 votes vote down vote up
public String checkDatePattern(String date) {
    DateTimeFormatter fmtr = DateTimeFormat.forPattern(PherfConstants.DEFAULT_DATE_PATTERN).withZone(DateTimeZone.UTC);;
    DateTime parsedDate = fmtr.parseDateTime(date);
    return fmtr.print(parsedDate);
}