Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Fail when parsing invalid local date #2134

Merged
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
Expand Up @@ -2,7 +2,11 @@

import java.text.ParseException;
import java.text.ParsePosition;
import java.util.*;
import java.util.Calendar;
import java.util.Date;
import java.util.GregorianCalendar;
import java.util.Locale;
import java.util.TimeZone;

/**
* Utilities methods for manipulating dates in iso8601 format. This is much much faster and GC friendly than using SimpleDateFormat so
Expand Down Expand Up @@ -147,9 +151,10 @@ public static Date parse(String date, ParsePosition pos) throws ParseException {

// if the value has no time component (and no time zone), we are done
boolean hasT = checkOffset(date, offset, 'T');

if (!hasT && (date.length() <= offset)) {
Calendar calendar = new GregorianCalendar(year, month - 1, day);
calendar.setLenient(false);

pos.setIndex(offset);
return calendar.getTime();
Expand Down
@@ -1,13 +1,18 @@
package com.google.gson.internal.bind.util;

import org.junit.Test;
import org.junit.function.ThrowingRunnable;
import java.text.ParseException;
import java.text.ParsePosition;
import java.util.*;

import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertThrows;
import static org.junit.Assert.fail;

import java.text.ParseException;
import java.text.ParsePosition;
import java.util.Calendar;
import java.util.Date;
import java.util.GregorianCalendar;
import java.util.Locale;
import java.util.TimeZone;
import org.junit.Test;
import org.junit.function.ThrowingRunnable;

public class ISO8601UtilsTest {

Expand Down Expand Up @@ -61,6 +66,26 @@ public void testDateParseWithDefaultTimezone() throws ParseException {
assertEquals(expectedDate, date);
}

@Test
public void testDateParseInvalidDay() {
String dateStr = "2022-12-33";
try {
ISO8601Utils.parse(dateStr, new ParsePosition(0));
fail("Expected parsing to fail");
} catch (ParseException expected) {
}
}

@Test
public void testDateParseInvalidMonth() {
String dateStr = "2022-14-30";
try {
ISO8601Utils.parse(dateStr, new ParsePosition(0));
fail("Expected parsing to fail");
} catch (ParseException expected) {
}
}

@Test
public void testDateParseWithTimezone() throws ParseException {
String dateStr = "2018-06-25T00:00:00-03:00";
Expand Down