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

The following examples show how to use org.joda.time.format.DateTimeFormatter#parseLocalDateTime() . 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: TestNewDateFunctions.java    From dremio-oss with Apache License 2.0 6 votes vote down vote up
@Test
public void testUnixTimeStampForDateWithPattern() throws Exception {
  DateTimeFormatter formatter = DateFunctionsUtils.getISOFormatterForFormatString("YYYY-MM-DD HH:MI:SS.FFF");
  date = formatter.parseLocalDateTime("2009-03-20 11:30:01.0");
  unixTimeStamp = com.dremio.common.util.DateTimes.toMillis(date) / 1000;

  testBuilder()
      .sqlQuery("select unix_timestamp('2009-03-20 11:30:01.0', 'YYYY-MM-DD HH:MI:SS.FFF') from cp.\"employee.json\" limit 1")
      .ordered()
      .baselineColumns("EXPR$0")
      .baselineValues(unixTimeStamp)
      .build().run();

  formatter = DateFunctionsUtils.getISOFormatterForFormatString("YYYY-MM-DD");
  date = formatter.parseLocalDateTime("2009-03-20");
  unixTimeStamp = com.dremio.common.util.DateTimes.toMillis(date) / 1000;

  testBuilder()
      .sqlQuery("select unix_timestamp('2009-03-20', 'YYYY-MM-DD') from cp.\"employee.json\" limit 1")
      .ordered()
      .baselineColumns("EXPR$0")
      .baselineValues(unixTimeStamp)
      .build().run();
}
 
Example 2
Source File: TestNewDateFunctions.java    From dremio-oss with Apache License 2.0 5 votes vote down vote up
@Test
public void testUnixTimeStampForDate() throws Exception {
  DateTimeFormatter formatter = DateFunctionsUtils.getISOFormatterForFormatString("YYYY-MM-DD HH24:MI:SS");
  date = formatter.parseLocalDateTime("2009-03-20 11:30:01");
  unixTimeStamp = com.dremio.common.util.DateTimes.toMillis(date) / 1000;
  testBuilder()
      .sqlQuery("select unix_timestamp('2009-03-20 11:30:01') from cp.\"employee.json\" limit 1")
      .ordered()
      .baselineColumns("EXPR$0")
      .baselineValues(unixTimeStamp)
      .build().run();

  date = formatter.parseLocalDateTime("2014-08-09 05:15:06");
  unixTimeStamp = com.dremio.common.util.DateTimes.toMillis(date) / 1000;
  testBuilder()
      .sqlQuery("select unix_timestamp('2014-08-09 05:15:06') from cp.\"employee.json\" limit 1")
      .ordered()
      .baselineColumns("EXPR$0")
      .baselineValues(unixTimeStamp)
      .build().run();

  date = formatter.parseLocalDateTime("1970-01-01 00:00:00");
  unixTimeStamp = com.dremio.common.util.DateTimes.toMillis(date) / 1000;
  testBuilder()
      .sqlQuery("select unix_timestamp('1970-01-01 00:00:00') from cp.\"employee.json\" limit 1")
      .ordered()
      .baselineColumns("EXPR$0")
      .baselineValues(unixTimeStamp)
      .build().run();

  // make sure we support 24 hour notation by default
  date = formatter.parseLocalDateTime("1970-01-01 23:12:12");
  unixTimeStamp = com.dremio.common.util.DateTimes.toMillis(date) / 1000;
  testBuilder()
    .sqlQuery("select unix_timestamp('1970-01-01 23:12:12') from cp.\"employee.json\" limit 1")
    .ordered()
    .baselineColumns("EXPR$0")
    .baselineValues(unixTimeStamp)
    .build().run();
}
 
Example 3
Source File: ParserUtils.java    From substitution-schedule-parser with Mozilla Public License 2.0 5 votes vote down vote up
static LocalDateTime parseDateTime(String string) {
    if (string == null) return null;
    reinitIfNeeded();

    string = string.replace("Stand:", "").replace("Import:", "").trim();
    int i = 0;
    for (DateTimeFormatter f : dateTimeFormatters) {
        try {
            LocalDateTime dt = f.parseLocalDateTime(string);
            if (dateTimeFormats[i].contains("yyyy")) {
                return dt;
            } else {
                Duration currentYearDifference = abs(new Duration(DateTime.now(), dt.toDateTime()));
                Duration lastYearDifference = abs(new Duration(DateTime.now(), dt.minusYears(1).toDateTime()));
                Duration nextYearDifference = abs(new Duration(DateTime.now(), dt.plusYears(1).toDateTime()));
                if (lastYearDifference.isShorterThan(currentYearDifference)) {
                    return DateTimeFormat.forPattern(dateTimeFormats[i])
                            .withLocale(Locale.GERMAN).withDefaultYear(f.getDefaultYear() - 1)
                            .parseLocalDateTime(string);
                } else if (nextYearDifference.isShorterThan(currentYearDifference)) {
                    return DateTimeFormat.forPattern(dateTimeFormats[i])
                            .withLocale(Locale.GERMAN).withDefaultYear(f.getDefaultYear() + 1)
                            .parseLocalDateTime(string);
                } else {
                    return dt;
                }
            }
        } catch (IllegalArgumentException e) {
            // Does not match this format, try the next one
        }
        i++;
    }
    // Does not match any known format :(
    return null;
}
 
Example 4
Source File: ProductFieldSetMapper.java    From website with GNU Affero General Public License v3.0 5 votes vote down vote up
private LocalDateTime getDateTime(String dateString) {
	if (!StringUtils.isBlank(dateString)) {
		String pattern;
		if (dateString.matches("(19|20)[0-9]{2}[/](0[1-9]|1[012])[/](0[1-9]|[12][0-9]|3[01])")) {
			pattern = "yyyy/MM/dd";
		} else {
			pattern = "yyyy-MM-dd";
		}
		DateTimeFormatter dateTimeFormatter = DateTimeFormat.forPattern(pattern);
		return dateTimeFormatter.parseLocalDateTime(dateString);
	}
	return null;
}
 
Example 5
Source File: CsvFileService.java    From website with GNU Affero General Public License v3.0 5 votes vote down vote up
private LocalDateTime getDateTime(String dateString) {
    if (!StringUtils.isBlank(dateString)) {
        String pattern;
        if (dateString.matches("(19|20)[0-9]{2}[/](0[1-9]|1[012])[/](0[1-9]|[12][0-9]|3[01])")) {
            pattern = "yyyy/MM/dd";
        } else {
            pattern = "yyyy-MM-dd";
        }
        DateTimeFormatter dateTimeFormatter = DateTimeFormat.forPattern(pattern);
        return dateTimeFormatter.parseLocalDateTime(dateString);
    }
    return null;
}
 
Example 6
Source File: TestHistogramGenerator.java    From dremio-oss with Apache License 2.0 4 votes vote down vote up
@Test
public void testTimeIntervals() throws Exception {
  HistogramGenerator hg = new HistogramGenerator(null);

  String myTimeStr = "2016-02-29 13:59:01";
  DateTimeFormatter dtf = DateFunctionsUtils.getISOFormatterForFormatString("YYYY-MM-DD HH24:MI:SS");
  LocalDateTime myTime = dtf.parseLocalDateTime(myTimeStr);
  System.out.println("Exact time: " + myTime + ", Month: " + myTime.getMonthOfYear());
  for (HistogramGenerator.TruncEvalEnum value : HistogramGenerator.TruncEvalEnum.getSortedAscValues()) {
    LocalDateTime roundedDown = hg.roundTime(myTime, value, true);
    LocalDateTime roundedUp = hg.roundTime(myTime, value, false);
    switch(value) {
      case SECOND:
        assertEquals(myTime, roundedDown);
        assertEquals(myTime, roundedUp);
        break;
      case MINUTE:
        assertEquals(dtf.parseLocalDateTime("2016-02-29 13:59:00"), roundedDown);
        assertEquals(dtf.parseLocalDateTime("2016-02-29 14:00:00"), roundedUp);
        break;
      case HOUR:
        assertEquals(dtf.parseLocalDateTime("2016-02-29 13:00:00"), roundedDown);
        assertEquals(dtf.parseLocalDateTime("2016-02-29 14:00:00"), roundedUp);
        break;
      case DAY:
        assertEquals(dtf.parseLocalDateTime("2016-02-29 00:00:00"), roundedDown);
        assertEquals(dtf.parseLocalDateTime("2016-03-01 00:00:00"), roundedUp);
        break;
      case WEEK:
        assertEquals(dtf.parseLocalDateTime("2016-02-29 00:00:00"), roundedDown);
        assertEquals(dtf.parseLocalDateTime("2016-03-07 00:00:00"), roundedUp);
        break;
      case MONTH:
        assertEquals(dtf.parseLocalDateTime("2016-02-01 00:00:00"), roundedDown);
        assertEquals(dtf.parseLocalDateTime("2016-03-01 00:00:00"), roundedUp);
        break;
      case QUARTER:
        assertEquals(dtf.parseLocalDateTime("2016-01-01 00:00:00"), roundedDown);
        assertEquals(dtf.parseLocalDateTime("2016-04-01 00:00:00"), roundedUp);
        break;
      case YEAR:
        assertEquals(dtf.parseLocalDateTime("2016-01-01 00:00:00"), roundedDown);
        assertEquals(dtf.parseLocalDateTime("2017-01-01 00:00:00"), roundedUp);
        break;
      case DECADE:
        assertEquals(dtf.parseLocalDateTime("2010-01-01 00:00:00"), roundedDown);
        assertEquals(dtf.parseLocalDateTime("2020-01-01 00:00:00"), roundedUp);
        break;
      case CENTURY:
        assertEquals(dtf.parseLocalDateTime("2000-01-01 00:00:00"), roundedDown);
        assertEquals(dtf.parseLocalDateTime("2100-01-01 00:00:00"), roundedUp);
        break;
      case MILLENNIUM:
        assertEquals(dtf.parseLocalDateTime("2000-01-01 00:00:00"), roundedDown);
        assertEquals(dtf.parseLocalDateTime("3000-01-01 00:00:00"), roundedUp);
        break;
      default:
        fail();
    }
  }
}
 
Example 7
Source File: ElasticBaseTestQuery.java    From dremio-oss with Apache License 2.0 4 votes vote down vote up
public static ColumnData[] getNullBusinessData() {
  final DateTimeFormatter formatter = DateFunctionsUtils.getSQLFormatterForFormatString("YYYY-MM-DD HH:MI:SS").withZone(DateTimeZone.UTC);
  final ElasticsearchCluster.ColumnData[] data = new ElasticsearchCluster.ColumnData[]{
    new ElasticsearchCluster.ColumnData("business_id", TEXT, new Object[][]{
      {null},
      {"abcde"},
      {"7890"},
      {"12345"},
      {"xyz"}
    }),
    new ElasticsearchCluster.ColumnData("full_address", TEXT, new Object[][]{
      {"12345 A Street, Cambridge, MA"},
      {null},
      {"987 B Street, San Diego, CA"},
      {"12345 A Street, Cambridge, MA"},
      {"12345 C Avenue, San Francisco, CA"}
    }),
    new ElasticsearchCluster.ColumnData("city", KEYWORD,
      new Object[][]{
        {"Cambridge"},
        {"San Francisco"},
        {null},
        {"Cambridge"},
        {"San Francisco"}
      }),
    new ElasticsearchCluster.ColumnData("city_analyzed", TEXT,
      new Object[][]{
        {"Cambridge"},
        {"San Francisco"},
        {null},
        {"Cambridge"},
        {"San Francisco"}
      }),
    new ElasticsearchCluster.ColumnData("state", KEYWORD,
      new Object[][]{
        {"MA"},
        {"CA"},
        {"CA"},
        {null},
        {"CA"}
      }),
    new ElasticsearchCluster.ColumnData("state_analyzed", TEXT, new Object[][]{
      {"MA"},
      {"CA"},
      {"CA"},
      {null},
      {"CA"}
    }),
    new ElasticsearchCluster.ColumnData("review_count", INTEGER, new Object[][]{
      {11},
      {22},
      {33},
      {11},
      {null}
    }),
    new ElasticsearchCluster.ColumnData("stars", FLOAT, new Object[][]{
      {null},
      {3.5f},
      {5.0f},
      {4.5f},
      {1}
    }),
    new ElasticsearchCluster.ColumnData("location_field", GEO_POINT, new Object[][]{
      {ImmutableMap.of("lat", 11, "lon", 11), ImmutableMap.of("lat", -11, "lon", -11)},
      {ImmutableMap.of("lat", 22, "lon", 22), ImmutableMap.of("lat", -22, "lon", -22)},
      {null},
      {ImmutableMap.of("lat", 44, "lon", 44), ImmutableMap.of("lat", -44, "lon", -44)},
      {ImmutableMap.of("lat", 55, "lon", 55), ImmutableMap.of("lat", -55, "lon", -55)}
    }),
    new ElasticsearchCluster.ColumnData("name", TEXT, new Object[][]{
      {"Store in Cambridge"},
      {"Store in San Francisco"},
      {"Store in San Diego"},
      {null},
      {"New store in San Francisco"},

    }),
    new ElasticsearchCluster.ColumnData("open", BOOLEAN, new Object[][] {
      {true},
      {true},
      {false},
      {true},
      {null}
    }),
    //withZoneRetainFields(DateTimeZone.getDefault())
    new ElasticsearchCluster.ColumnData("datefield", DATE, new Object[][] {
      {formatter.parseLocalDateTime("2014-02-10 10:50:42")},
      {null},
      {formatter.parseLocalDateTime("2014-02-12 10:50:42")},
      {formatter.parseLocalDateTime("2014-02-11 10:50:42")},
      {formatter.parseLocalDateTime("2014-02-10 10:50:42")}
    })
  };
  return data;
}
 
Example 8
Source File: RSSTypeTest.java    From mamute with Apache License 2.0 4 votes vote down vote up
@Test
public void should_verify_date_format_onde_trabalhar() {
	DateTimeFormatter dateFormat = RSSType.ONDE_TRABALHAR.getDateFormat();
	LocalDateTime time = dateFormat.parseLocalDateTime("Wed, 27 Nov 2013 11:56:05 +0000");
	time(time);
}
 
Example 9
Source File: RSSTypeTest.java    From mamute with Apache License 2.0 4 votes vote down vote up
@Test
public void should_verify_date_format_info_q() {
	DateTimeFormatter dateFormat = RSSType.INFO_Q.getDateFormat();
	LocalDateTime time = dateFormat.parseLocalDateTime("Wed, 27 Nov 2013 11:56:05 GMT");
	time(time);
}
 
Example 10
Source File: JodaLocalDateTimeCodec.java    From actframework with Apache License 2.0 4 votes vote down vote up
@Override
protected LocalDateTime parse(DateTimeFormatter formatter, String value) {
    String amended = (isIso && !value.endsWith("Z")) ? value + "Z" : value;
    return formatter.parseLocalDateTime(amended);
}
 
Example 11
Source File: LocalDateTimeConverter.java    From gson-jodatime-serialisers with MIT License 3 votes vote down vote up
/**
 * Gson invokes this call-back method during deserialization when it encounters a field of the
 * specified type. <p>
 *
 * In the implementation of this call-back method, you should consider invoking
 * {@link JsonDeserializationContext#deserialize(JsonElement, Type)} method to create objects
 * for any non-trivial field of the returned object. However, you should never invoke it on the
 * the same type passing {@code json} since that will cause an infinite loop (Gson will call your
 * call-back method again).
 * @param json The Json data being deserialized
 * @param typeOfT The type of the Object to deserialize to
 * @return a deserialized object of the specified type typeOfT which is a subclass of {@code T}
 * @throws JsonParseException if json is not in the expected format of {@code typeOfT}
 */
@Override
public LocalDateTime deserialize(JsonElement json, Type typeOfT, JsonDeserializationContext context)
    throws JsonParseException
{
  // Do not try to deserialize null or empty values
  if (json.getAsString() == null || json.getAsString().isEmpty())
  {
    return null;
  }

  final DateTimeFormatter fmt = DateTimeFormat.forPattern(PATTERN);
  return fmt.parseLocalDateTime(json.getAsString());
}
 
Example 12
Source File: Time_12_LocalDateTime_t.java    From coming with MIT License 2 votes vote down vote up
/**
 * Parses a {@code LocalDateTime} from the specified string using a formatter.
 * 
 * @param str  the string to parse, not null
 * @param formatter  the formatter to use, not null
 * @since 2.0
 */
public static LocalDateTime parse(String str, DateTimeFormatter formatter) {
    return formatter.parseLocalDateTime(str);
}
 
Example 13
Source File: Time_12_LocalDateTime_s.java    From coming with MIT License 2 votes vote down vote up
/**
 * Parses a {@code LocalDateTime} from the specified string using a formatter.
 * 
 * @param str  the string to parse, not null
 * @param formatter  the formatter to use, not null
 * @since 2.0
 */
public static LocalDateTime parse(String str, DateTimeFormatter formatter) {
    return formatter.parseLocalDateTime(str);
}
 
Example 14
Source File: LocalDateTime.java    From astor with GNU General Public License v2.0 2 votes vote down vote up
/**
 * Parses a {@code LocalDateTime} from the specified string using a formatter.
 * 
 * @param str  the string to parse, not null
 * @param formatter  the formatter to use, not null
 * @since 2.0
 */
public static LocalDateTime parse(String str, DateTimeFormatter formatter) {
    return formatter.parseLocalDateTime(str);
}
 
Example 15
Source File: LocalDateTime.java    From astor with GNU General Public License v2.0 2 votes vote down vote up
/**
 * Parses a {@code LocalDateTime} from the specified string using a formatter.
 * 
 * @param str  the string to parse, not null
 * @param formatter  the formatter to use, not null
 * @since 2.0
 */
public static LocalDateTime parse(String str, DateTimeFormatter formatter) {
    return formatter.parseLocalDateTime(str);
}