/** * Convert a String into a <code>Number</code> object. * @param sourceType the source type of the conversion * @param targetType The type to convert the value to * @param value The String date value. * @param format The NumberFormat to parse the String value. * * @return The converted Number object. * @throws ConversionException if the String cannot be converted. */ private Number parse(final Class<?> sourceType, final Class<?> targetType, final String value, final NumberFormat format) { final ParsePosition pos = new ParsePosition(0); final Number parsedNumber = format.parse(value, pos); if (pos.getErrorIndex() >= 0 || pos.getIndex() != value.length() || parsedNumber == null) { String msg = "Error converting from '" + toString(sourceType) + "' to '" + toString(targetType) + "'"; if (format instanceof DecimalFormat) { msg += " using pattern '" + ((DecimalFormat)format).toPattern() + "'"; } if (locale != null) { msg += " for locale=[" + locale + "]"; } if (log().isDebugEnabled()) { log().debug(" " + msg); } throw new ConversionException(msg); } return parsedNumber; }
@Test(dataProvider="ReducedWithChrono") public void test_reducedWithChronoYear(ChronoLocalDate date) { Chronology chrono = date.getChronology(); DateTimeFormatter df = new DateTimeFormatterBuilder().appendValueReduced(YEAR, 2, 2, LocalDate.of(2000, 1, 1)) .toFormatter() .withChronology(chrono); int expected = date.get(YEAR); String input = df.format(date); ParsePosition pos = new ParsePosition(0); TemporalAccessor parsed = df.parseUnresolved(input, pos); int actual = parsed.get(YEAR); assertEquals(actual, expected, String.format("Wrong date parsed, chrono: %s, input: %s", chrono, input)); }
private void processAndAddData(final Realm realm, final String sectionKey, final List<NYTimesStory> stories) { if (stories.isEmpty()) return; realm.executeTransactionAsync(r -> { for (NYTimesStory story : stories) { Date parsedPublishedDate = inputDateFormat.parse(story.getPublishedDate(), new ParsePosition(0)); story.setSortTimeStamp(parsedPublishedDate.getTime()); story.setPublishedDate(outputDateFormat.format(parsedPublishedDate)); // Find existing story in Realm (if any) // If it exists, we need to merge the local state with the remote, because the local state // contains more info than is available on the server. NYTimesStory persistedStory = r.where(NYTimesStory.class).equalTo(NYTimesStory.URL, story.getUrl()).findFirst(); if (persistedStory != null) { // Only local state is the `read` boolean. story.setRead(persistedStory.isRead()); } // Only create or update the local story if needed if (persistedStory == null || !persistedStory.getUpdatedDate().equals(story.getUpdatedDate())) { story.setApiSection(sectionKey); r.copyToRealmOrUpdate(story); } } }, throwable -> Timber.e(throwable, "Could not save data")); }
@Test(dataProvider="parseData") public void test_parse_textField(int minWidth, int maxWidth, SignStyle signStyle, int subsequentWidth, String text, int pos, int expectedPos, long expectedValue) { ParsePosition ppos = new ParsePosition(pos); DateTimeFormatter dtf = getFormatter(DAY_OF_WEEK, minWidth, maxWidth, signStyle); if (subsequentWidth > 0) { // hacky, to reserve space dtf = builder.appendValue(DAY_OF_YEAR, subsequentWidth).toFormatter(locale).withDecimalStyle(decimalStyle); } TemporalAccessor parsed = dtf.parseUnresolved(text, ppos); if (ppos.getErrorIndex() != -1) { assertEquals(ppos.getErrorIndex(), expectedPos); } else { assertTrue(subsequentWidth >= 0); assertEquals(ppos.getIndex(), expectedPos + subsequentWidth); assertEquals(parsed.getLong(DAY_OF_WEEK), expectedValue); assertEquals(parsed.query(TemporalQueries.chronology()), null); assertEquals(parsed.query(TemporalQueries.zoneId()), null); } }
public void testParseRfc3339Examples() throws java.text.ParseException { // Two digit milliseconds. Date d = ISO8601Utils.parse("1985-04-12T23:20:50.52Z", new ParsePosition(0)); assertEquals(newDate(1985, 4, 12, 23, 20, 50, 520, 0), d); d = ISO8601Utils.parse("1996-12-19T16:39:57-08:00", new ParsePosition(0)); assertEquals(newDate(1996, 12, 19, 16, 39, 57, 0, -8 * 60), d); // Truncated leap second. d = ISO8601Utils.parse("1990-12-31T23:59:60Z", new ParsePosition(0)); assertEquals(newDate(1990, 12, 31, 23, 59, 59, 0, 0), d); // Truncated leap second. d = ISO8601Utils.parse("1990-12-31T15:59:60-08:00", new ParsePosition(0)); assertEquals(newDate(1990, 12, 31, 15, 59, 59, 0, -8 * 60), d); // Two digit milliseconds. d = ISO8601Utils.parse("1937-01-01T12:00:27.87+00:20", new ParsePosition(0)); assertEquals(newDate(1937, 1, 1, 12, 0, 27, 870, 20), d); }
/** * Parses and resolves the specified text. * <p> * This parses to a {@code TemporalAccessor} ensuring that the text is fully parsed. * * @param text the text to parse, not null * @param position the position to parse from, updated with length parsed * and the index of any error, null if parsing whole string * @return the resolved result of the parse, not null * @throws DateTimeParseException if the parse fails * @throws DateTimeException if an error occurs while resolving the date or time * @throws IndexOutOfBoundsException if the position is invalid */ private TemporalAccessor parseResolved0(final CharSequence text, final ParsePosition position) { ParsePosition pos = (position != null ? position : new ParsePosition(0)); DateTimeParseContext context = parseUnresolved0(text, pos); if (context == null || pos.getErrorIndex() >= 0 || (position == null && pos.getIndex() < text.length())) { String abbr; if (text.length() > 64) { abbr = text.subSequence(0, 64).toString() + "..."; } else { abbr = text.toString(); } if (pos.getErrorIndex() >= 0) { throw new DateTimeParseException("Text '" + abbr + "' could not be parsed at index " + pos.getErrorIndex(), text, pos.getErrorIndex()); } else { throw new DateTimeParseException("Text '" + abbr + "' could not be parsed, unparsed text found at index " + pos.getIndex(), text, pos.getIndex()); } } return context.toResolved(resolverStyle, resolverFields); }
@Test(dataProvider="ReducedWithChrono") public void test_reducedWithChronoYearOfEra(ChronoLocalDate date) { Chronology chrono = date.getChronology(); DateTimeFormatter df = new DateTimeFormatterBuilder().appendValueReduced(YEAR_OF_ERA, 2, 2, LocalDate.of(2000, 1, 1)) .toFormatter() .withChronology(chrono); int expected = date.get(YEAR_OF_ERA); String input = df.format(date); ParsePosition pos = new ParsePosition(0); TemporalAccessor parsed = df.parseUnresolved(input, pos); int actual = parsed.get(YEAR_OF_ERA); assertEquals(actual, expected, String.format("Wrong date parsed, chrono: %s, input: %s", chrono, input)); }
@Test public void test_reducedWithLateChronoChange() { ThaiBuddhistDate date = ThaiBuddhistDate.of(2543, 1, 1); DateTimeFormatter df = new DateTimeFormatterBuilder() .appendValueReduced(YEAR, 2, 2, LocalDate.of(2000, 1, 1)) .appendLiteral(" ") .appendChronologyId() .toFormatter(); int expected = date.get(YEAR); String input = df.format(date); ParsePosition pos = new ParsePosition(0); TemporalAccessor parsed = df.parseUnresolved(input, pos); assertEquals(pos.getIndex(), input.length(), "Input not parsed completely"); assertEquals(pos.getErrorIndex(), -1, "Error index should be -1 (no-error)"); int actual = parsed.get(YEAR); assertEquals(actual, expected, String.format("Wrong date parsed, chrono: %s, input: %s", parsed.query(TemporalQueries.chronology()), input)); }
@Override public java.sql.Date read(JsonReader in) throws IOException { switch (in.peek()) { case NULL: in.nextNull(); return null; default: String date = in.nextString(); try { if (dateFormat != null) { return new java.sql.Date(dateFormat.parse(date).getTime()); } return new java.sql.Date(ISO8601Utils.parse(date, new ParsePosition(0)).getTime()); } catch (ParseException e) { throw new JsonParseException(e); } } }
/** * Implement SymbolTable API. Parse out a symbol reference * name. */ @Override public String parseReference(String text, ParsePosition pos, int limit) { int start = pos.getIndex(); int i = start; while (i < limit) { char c = text.charAt(i); if ((i==start && !UCharacter.isUnicodeIdentifierStart(c)) || !UCharacter.isUnicodeIdentifierPart(c)) { break; } ++i; } if (i == start) { // No valid name chars return null; } pos.setIndex(i); return text.substring(start, i); }
@Test public void test_parse_CharSequence_ParsePosition_resolved() { DateTimeFormatter test = DateTimeFormatter.ISO_DATE; ParsePosition pos = new ParsePosition(3); TemporalAccessor result = test.parse("XXX2012-06-30XXX", pos); assertEquals(pos.getIndex(), 13); assertEquals(pos.getErrorIndex(), -1); assertEquals(result.isSupported(YEAR), true); assertEquals(result.isSupported(MONTH_OF_YEAR), true); assertEquals(result.isSupported(DAY_OF_MONTH), true); assertEquals(result.isSupported(HOUR_OF_DAY), false); assertEquals(result.getLong(YEAR), 2012L); assertEquals(result.getLong(MONTH_OF_YEAR), 6L); assertEquals(result.getLong(DAY_OF_MONTH), 30L); assertEquals(result.query(LocalDate::from), LocalDate.of(2012, 6, 30)); }
@Test public void test_reducedWithLateChronoChangeTwice() { DateTimeFormatter df = new DateTimeFormatterBuilder() .appendValueReduced(YEAR, 2, 2, LocalDate.of(2000, 1, 1)) .appendLiteral(" ") .appendChronologyId() .appendLiteral(" ") .appendChronologyId() .toFormatter(); int expected = 2044; String input = "44 ThaiBuddhist ISO"; ParsePosition pos = new ParsePosition(0); TemporalAccessor parsed = df.parseUnresolved(input, pos); assertEquals(pos.getIndex(), input.length(), "Input not parsed completely: " + pos); assertEquals(pos.getErrorIndex(), -1, "Error index should be -1 (no-error)"); int actual = parsed.get(YEAR); assertEquals(actual, expected, String.format("Wrong date parsed, chrono: %s, input: %s", parsed.query(TemporalQueries.chronology()), input)); }
@Test(dataProvider="bigOffsets") public void test_parse_bigOffsets(String pattern, String parse, long offsetSecs) throws Exception { ParsePosition pos = new ParsePosition(0); TemporalAccessor parsed = getFormatter(pattern, "").parseUnresolved(parse, pos); assertEquals(pos.getIndex(), parse.length()); assertEquals(parsed.getLong(OFFSET_SECONDS), offsetSecs); }
public void test_parse_noMatch_atEnd() throws Exception { ParsePosition pos = new ParsePosition(6); TemporalAccessor parsed = getFormatter(DAY_OF_WEEK, TextStyle.FULL).parseUnresolved("Monday", pos); assertEquals(pos.getErrorIndex(), 6); assertEquals(parsed, null); }
private static TextFormatter<String> createDecimalFormatter() { DecimalFormat format = new DecimalFormat("#.0"); format.setNegativePrefix("-"); return new TextFormatter<>(c -> { if (c.getControlNewText().isEmpty()) return c; ParsePosition pos = new ParsePosition(0); Number result = format.parse(c.getControlNewText(), pos); if (result == null || pos.getIndex() < c.getControlNewText().length()) { return null; } else return c; }); }
@Test(dataProvider="offsets") public void test_parse_midStringMatch(String pattern, String parse, ZoneOffset expected) throws Exception { ParsePosition pos = new ParsePosition(5); TemporalAccessor parsed = getFormatter(pattern, "Z").parseUnresolved("OTHER" + parse + ":OTHER", pos); assertEquals(pos.getIndex(), parse.length() + 5); assertParsed(parsed, expected); }
public void test_parse_remainderIgnored() throws Exception { ParsePosition pos = new ParsePosition(0); assertEquals(getFormatter(DAY_OF_WEEK, TextStyle.SHORT) .parseUnresolved("Wednesday", pos) .getLong(DAY_OF_WEEK), 3L); assertEquals(pos.getIndex(), 3); }
@Test(dataProvider="success") public void test_parse_success(String s, boolean caseSensitive, String text, int pos, int expectedPos) { setCaseSensitive(caseSensitive); ParsePosition ppos = new ParsePosition(pos); TemporalAccessor parsed = getFormatter(s).parseUnresolved(text, ppos); if (ppos.getErrorIndex() != -1) { assertEquals(ppos.getIndex(), expectedPos); } else { assertEquals(ppos.getIndex(), expectedPos); assertEquals(parsed.isSupported(YEAR), false); assertEquals(parsed.query(TemporalQueries.chronology()), null); assertEquals(parsed.query(TemporalQueries.zoneId()), null); } }
@Test(dataProvider="sample_isoLocalDateTime") public void test_parse_isoLocalDateTime( Integer year, Integer month, Integer day, Integer hour, Integer min, Integer sec, Integer nano, String offsetId, String zoneId, String input, Class<?> invalid) { if (input != null) { Expected expected = createDateTime(year, month, day, hour, min, sec, nano); assertParseMatch(DateTimeFormatter.ISO_LOCAL_DATE_TIME.parseUnresolved(input, new ParsePosition(0)), expected); } }
@Test public void test_appendValue_subsequent2_parse5() throws Exception { builder.appendValue(MONTH_OF_YEAR, 1, 2, SignStyle.NORMAL).appendValue(DAY_OF_MONTH, 2).appendLiteral('4'); DateTimeFormatter f = builder.toFormatter(); assertEquals(f.toString(), "Value(MonthOfYear,1,2,NORMAL)Value(DayOfMonth,2)'4'"); TemporalAccessor parsed = f.parseUnresolved("01234", new ParsePosition(0)); assertEquals(parsed.getLong(MONTH_OF_YEAR), 1L); assertEquals(parsed.getLong(DAY_OF_MONTH), 23L); }
@Test(dataProvider="Nanos") public void test_reverseParse_noDecimalPoint(int minWidth, int maxWidth, int value, String result) throws Exception { ParsePosition pos = new ParsePosition((result.startsWith(".") ? 1 : 0)); TemporalAccessor parsed = getFormatter(NANO_OF_SECOND, minWidth, maxWidth, false).parseUnresolved(result, pos); assertEquals(pos.getIndex(), result.length()); int expectedValue = fixParsedValue(maxWidth, value); assertParsed(parsed, NANO_OF_SECOND, value == 0 && minWidth == 0 ? null : (long) expectedValue); }
@Test(dataProvider="parseText") public void test_parse_strict_caseSensitive_parseUpper(TemporalField field, TextStyle style, int value, String input) throws Exception { if (input.equals(input.toUpperCase(Locale.ROOT))) { // Skip if the given input is all upper case (e.g., "Q1") return; } setCaseSensitive(true); ParsePosition pos = new ParsePosition(0); getFormatter(field, style).parseUnresolved(input.toUpperCase(Locale.ROOT), pos); assertEquals(pos.getErrorIndex(), 0); }
public void test_parse_noMatch2() throws Exception { ParsePosition pos = new ParsePosition(3); TemporalAccessor parsed = getFormatter(DAY_OF_WEEK, TextStyle.FULL).parseUnresolved("Monday", pos); assertEquals(pos.getErrorIndex(), 3); assertEquals(parsed, null); }
/** * Insert formats back into the pattern for toPattern() support. * * @param pattern source * @param customPatterns The custom patterns to re-insert, if any * @return full pattern */ private String insertFormats(String pattern, ArrayList customPatterns) { if (!containsElements(customPatterns)) { return pattern; } StrBuilder sb = new StrBuilder(pattern.length() * 2); ParsePosition pos = new ParsePosition(0); int fe = -1; int depth = 0; while (pos.getIndex() < pattern.length()) { char c = pattern.charAt(pos.getIndex()); switch (c) { case QUOTE: appendQuotedString(pattern, pos, sb, false); break; case START_FE: depth++; if (depth == 1) { fe++; sb.append(START_FE).append( readArgumentIndex(pattern, next(pos))); String customPattern = (String) customPatterns.get(fe); if (customPattern != null) { sb.append(START_FMT).append(customPattern); } } break; case END_FE: depth--; //$FALL-THROUGH$ default: sb.append(c); next(pos); } } return sb.toString(); }
@Test public void test_adjacent_strict_firstVariableWidth_success() throws Exception { // succeeds greedily parsing variable width, then fixed width, to non-numeric Z DateTimeFormatter f = builder.appendValue(HOUR_OF_DAY).appendValue(MINUTE_OF_HOUR, 2).appendLiteral('Z').toFormatter(Locale.UK); ParsePosition pp = new ParsePosition(0); TemporalAccessor parsed = f.parseUnresolved("12309Z", pp); assertEquals(pp.getErrorIndex(), -1); assertEquals(pp.getIndex(), 6); assertEquals(parsed.getLong(HOUR_OF_DAY), 123L); assertEquals(parsed.getLong(MINUTE_OF_HOUR), 9L); }
public void test_parse_caseInsensitiveUTC_matchedCase() throws Exception { setCaseSensitive(false); ParsePosition pos = new ParsePosition(0); TemporalAccessor parsed = getFormatter("+HH:MM:ss", "Z").parseUnresolved("Z", pos); assertEquals(pos.getIndex(), 1); assertParsed(parsed, ZoneOffset.UTC); }
@Test(dataProvider="offsets") public void test_parse_midStringMatch_EmptyUTC(String pattern, String parse, ZoneOffset expected) throws Exception { ParsePosition pos = new ParsePosition(5); TemporalAccessor parsed = getFormatter(pattern, "").parseUnresolved("OTHER" + parse + ":OTHER", pos); assertEquals(pos.getIndex(), parse.length() + 5); assertParsed(parsed, expected); }
@Test public void test_parse_weekDate_largeYear() { TemporalAccessor parsed = DateTimeFormatter.ISO_WEEK_DATE.parseUnresolved("+123456-W04-5", new ParsePosition(0)); assertEquals(parsed.getLong(IsoFields.WEEK_BASED_YEAR), 123456L); assertEquals(parsed.getLong(IsoFields.WEEK_OF_WEEK_BASED_YEAR), 4L); assertEquals(parsed.getLong(DAY_OF_WEEK), 5L); }
@Test(expectedExceptions=NullPointerException.class) public void test_toFormat_parseObject_StringParsePosition_nullString() throws Exception { // SimpleDateFormat has this behavior DateTimeFormatter test = fmt.withLocale(Locale.ENGLISH).withDecimalStyle(DecimalStyle.STANDARD); Format format = test.toFormat(); ParsePosition pos = new ParsePosition(0); format.parseObject((String) null, pos); }
@Test(dataProvider="offsets") public void test_parse_startStringMatch(String pattern, String parse, ZoneOffset expected) throws Exception { ParsePosition pos = new ParsePosition(0); TemporalAccessor parsed = getFormatter(pattern, "Z").parseUnresolved(parse + ":OTHER", pos); assertEquals(pos.getIndex(), parse.length()); assertParsed(parsed, expected); }
@Test public void test_adjacent_strict_firstFixedWidth() throws Exception { // succeeds because both number elements are fixed width DateTimeFormatter f = builder.appendValue(HOUR_OF_DAY, 2).appendValue(MINUTE_OF_HOUR, 2).appendLiteral('9').toFormatter(Locale.UK); ParsePosition pp = new ParsePosition(0); TemporalAccessor parsed = f.parseUnresolved("12309", pp); assertEquals(pp.getErrorIndex(), -1); assertEquals(pp.getIndex(), 5); assertEquals(parsed.getLong(HOUR_OF_DAY), 12L); assertEquals(parsed.getLong(MINUTE_OF_HOUR), 30L); }
public static void main(String[] args) throws ParseException { String pat1 = "yyyy-MM-dd HH:mm:ss" ; /*Date date = new Date(); SimpleDateFormat sdf = new SimpleDateFormat(pat1); System.out.println(date);*/ Date currentTime = new Date(); SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); String dateString = formatter.format(currentTime); ParsePosition pos = new ParsePosition(8); Date currentTime_2 = formatter.parse(dateString, pos); System.out.println(currentTime_2); // System.out.println(DateUtils.parseDate(dateTime)); //System.out.println(DateUtils.parseDate(DateUtils.time(now()))); //System.out.println(createDate.toString()); /*SimpleDateFormat sdf = new SimpleDateFormat(pat1); System.out.println(sdf.parse("2016-3-3 13:30:0"));*/ //Calendar cal = Calendar.getInstance(); // System.out.println(now(COMPACT_YMDHMS_FORMAT)); // System.out.println(time2Str(now())); // System.out.println(DateUtils.time(now()).toString("yyyy年MM月dd日HH时mm分ss秒")); //System.out.println(DateUtils.time(now()).toString(DEFAULT_YMDHMS_FORMAT)); /*System.out.println( lengthBetween( time("2013-04-20 11:15:15"), time("2013-04-18 11:15:15"), JodaTime.DAY ) ); System.out.println(time2Str(new Date(), DEFAULT_YMDHMS_FORMAT)); System.out.println(currentTime());*/ }
@Test(expectedExceptions=DateTimeParseException.class) public void test_parse_CharSequence_ParsePosition_parseError() { DateTimeFormatter test = DateTimeFormatter.ISO_DATE; ParsePosition pos = new ParsePosition(3); try { test.parse("XXX2012XXX", pos); fail(); } catch (DateTimeParseException ex) { assertEquals(ex.getErrorIndex(), 7); throw ex; } }
@Test(dataProvider = "adjacentValuePatterns1") public void test_adjacentValuePatterns1(String pattern, TemporalField field1, TemporalField field2, String text, int expected1, int expected2) { DateTimeFormatter df = new DateTimeFormatterBuilder() .appendPattern(pattern).toFormatter(Locale.US); ParsePosition ppos = new ParsePosition(0); TemporalAccessor parsed = df.parseUnresolved(text, ppos); assertEquals(parsed.get(field1), expected1); assertEquals(parsed.get(field2), expected2); }
@Test(dataProvider="sample_isoInstant") public void test_parse_isoInstant( long instantSecs, Integer nano, String input, Class<?> invalid) { if (input != null) { TemporalAccessor parsed = DateTimeFormatter.ISO_INSTANT.parseUnresolved(input, new ParsePosition(0)); assertEquals(parsed.getLong(INSTANT_SECONDS), instantSecs); assertEquals(parsed.getLong(NANO_OF_SECOND), (nano == null ? 0 : nano)); } }
@Test public void test_parseUnresolved_StringParsePosition_duplicateFieldSameValue() { DateTimeFormatter test = new DateTimeFormatterBuilder() .appendValue(MONTH_OF_YEAR).appendLiteral('-').appendValue(MONTH_OF_YEAR).toFormatter(); ParsePosition pos = new ParsePosition(3); TemporalAccessor result = test.parseUnresolved("XXX6-6", pos); assertEquals(pos.getIndex(), 6); assertEquals(pos.getErrorIndex(), -1); assertEquals(result.getLong(MONTH_OF_YEAR), 6); }