Skip to content

Commit

Permalink
Fail when parsing invalid local date (#2134)
Browse files Browse the repository at this point in the history
* Fail when parsing invalid local date

* Improve invalid date tests
  • Loading branch information
Marcono1234 committed Jun 16, 2022
1 parent 96ab171 commit 57225c6
Show file tree
Hide file tree
Showing 2 changed files with 38 additions and 8 deletions.
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

0 comments on commit 57225c6

Please sign in to comment.