Java Code Examples for android.icu.text.SimpleDateFormat#parse()

The following examples show how to use android.icu.text.SimpleDateFormat#parse() . 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: DateFormatRegressionTest.java    From j2objc with Apache License 2.0 6 votes vote down vote up
/**
 * @bug 4104522
 * CANNOT REPRODUCE
 * According to the bug report, this test should throw a
 * StringIndexOutOfBoundsException during the second parse.  However,
 * this is not seen.
 */
@Test
public void Test4104522() {
    SimpleDateFormat sdf = new SimpleDateFormat();
    String pattern = "'time' hh:mm";
    sdf.applyPattern(pattern);
    logln("pattern: \"" + pattern + "\"");
    // works correctly
    ParsePosition pp = new ParsePosition(0);
    String text = "time ";
    Date dt = sdf.parse(text, pp);
    logln(" text: \"" + text + "\"" + " date: " + dt);
    // works wrong
    pp.setIndex(0);
    text = "time";
    dt = sdf.parse(text, pp);
    logln(" text: \"" + text + "\"" + " date: " + dt);    
}
 
Example 2
Source File: CalendarRegressionTest.java    From j2objc with Apache License 2.0 6 votes vote down vote up
@Test
public void Test4061476() {
    SimpleDateFormat fmt = new SimpleDateFormat("ddMMMyy", Locale.UK);
    Calendar cal = GregorianCalendar.getInstance(TimeZone.getTimeZone("GMT"), 
                                                 Locale.UK);
    fmt.setCalendar(cal);
    try
        {
            Date date = fmt.parse("29MAY97");
            cal.setTime(date);
        }
    catch (Exception e) {
        System.out.print("");
    }
    cal.set(Calendar.HOUR_OF_DAY, 13);
    logln("Hour: "+cal.get(Calendar.HOUR_OF_DAY));
    cal.add(Calendar.HOUR_OF_DAY, 6);
    logln("Hour: "+cal.get(Calendar.HOUR_OF_DAY));
    if (cal.get(Calendar.HOUR_OF_DAY) != 19)
        errln("Fail: Want 19 Got " + cal.get(Calendar.HOUR_OF_DAY));
}
 
Example 3
Source File: CalendarRegressionTest.java    From j2objc with Apache License 2.0 6 votes vote down vote up
/**
 * Test case for ticket 9968
 * subparse fails to return an error indication when start pos is 0 
 */
@Test
public void TestT9968() {
    SimpleDateFormat sdf0 = new SimpleDateFormat("-MMMM");
    ParsePosition pos0 = new ParsePosition(0);
    /* Date d0 = */ sdf0.parse("-September", pos0);
    logln("sdf0: " + pos0.getErrorIndex() + "/" + pos0.getIndex());
    assertTrue("Fail: failed a good test", pos0.getErrorIndex() == -1);

    SimpleDateFormat sdf1 = new SimpleDateFormat("-MMMM");
    ParsePosition pos1 = new ParsePosition(0);
    /* Date d1 = */ sdf1.parse("-????", pos1);
    logln("sdf1: " + pos1.getErrorIndex() + "/" + pos1.getIndex());
    assertTrue("Fail: failed to detect bad parse", pos1.getErrorIndex() == 1);

    SimpleDateFormat sdf2 = new SimpleDateFormat("MMMM");
    ParsePosition pos2 = new ParsePosition(0);
    /* Date d2 = */ sdf2.parse("????", pos2);
    logln("sdf2: " + pos2.getErrorIndex() + "/" + pos2.getIndex());
    assertTrue("Fail: failed to detect bad parse", pos2.getErrorIndex() == 0);
}
 
Example 4
Source File: DateFormatRegressionTest.java    From j2objc with Apache License 2.0 6 votes vote down vote up
@Test
public void TestT10906()
{
    String pattern = new String("MM-dd-yyyy");
    String text = new String("06-10-2014");
    SimpleDateFormat format = new SimpleDateFormat(pattern);
    ParsePosition pp = new ParsePosition(-1);
    try {
        format.parse(text, pp);
        int errorIdx = pp.getErrorIndex();
        if (errorIdx == -1) {          
            errln("failed to report invalid (negative) starting parse position");
        }
    } catch(StringIndexOutOfBoundsException e) {
        errln("failed to fix invalid (negative) starting parse position");
    }

}
 
Example 5
Source File: DateFormatRegressionTest.java    From j2objc with Apache License 2.0 6 votes vote down vote up
/**
 * @bug 4151706
 * 'z' at end of date format throws index exception in SimpleDateFormat
 * CANNOT REPRODUCE THIS BUG ON 1.2FCS
 */
@Test
public void Test4151706() {
    String dateString = "Thursday, 31-Dec-98 23:00:00 GMT";
    SimpleDateFormat fmt = new SimpleDateFormat("EEEE, dd-MMM-yy HH:mm:ss z", Locale.US);
    Calendar cal = Calendar.getInstance(TimeZone.getTimeZone("UTC"), Locale.US);
    cal.clear();
    cal.set(1998, Calendar.DECEMBER, 31, 23, 0, 0);
    Date d = new Date();
    try {
        d = fmt.parse(dateString);
        // {sfb} what about next two lines?
        if (d.getTime() != cal.getTime().getTime())
            errln("Incorrect value: " + d);
    } catch (Exception e) {
        errln("Fail: " + e);
    }
    StringBuffer temp = new StringBuffer("");
    FieldPosition pos = new FieldPosition(0);
    logln(dateString + " . " + fmt.format(d, temp, pos));
}
 
Example 6
Source File: DateFormatRegressionTestJ.java    From j2objc with Apache License 2.0 6 votes vote down vote up
@Test
public void Test4468663() {
    Date d =new Date(-93716671115767L);
    String origin_d = d.toString();
    String str;
    final String pattern = new String("EEEE, MMMM d, yyyy");
    SimpleDateFormat sdf = new SimpleDateFormat(pattern);

    if (sdf.getTimeZone().useDaylightTime()) {
        logln("original date: " + origin_d.toString());
        str = sdf.format(d);
        logln(" after format----->" + str);
        
        d = sdf.parse(str, new ParsePosition(0));
        logln(" after parse----->" + d.toString());

        str = sdf.format(d);
        logln(" after format----->" + str);

        d = sdf.parse(str, new ParsePosition(0));
        logln(" after parse----->" + d.toString());

        str = sdf.format(d);
        logln(" after format----->" + str);        
    }
}
 
Example 7
Source File: DateFormatRegressionTestJ.java    From j2objc with Apache License 2.0 6 votes vote down vote up
public void run() {
    SimpleDateFormat sdf = (SimpleDateFormat) sdf_.clone();
    TimeZone defaultTZ = TimeZone.getDefault();
    TimeZone PST = TimeZone.getTimeZone("PST");
    int defaultOffset = defaultTZ.getRawOffset();
    int PSTOffset = PST.getRawOffset();
    int offset = defaultOffset - PSTOffset;
    long ms = UTC_LONG - offset;
    try {
        int i = 0;
        while (i < 10000) {
            Date date = sdf.parse(TIME_STRING);
            long t = date.getTime();
            i++;
            if (t != ms) {
                throw new ParseException("Parse Error: " + i + " (" + sdf.format(date) 
                          + ") " + t + " != " + ms, 0);
            }
        }
    } catch (Exception e) {
        errln("parse error: " + e.getMessage());
    }
}
 
Example 8
Source File: IslamicTest.java    From j2objc with Apache License 2.0 5 votes vote down vote up
@Test
public void TestIslamicTabularDates() {
    SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd");
    Date date = null;
    try {
        date = formatter.parse("1975-05-06");
    }catch(Exception e){
        errln("unable to parse test date string - errMsg:" +e.getLocalizedMessage());
    }

    IslamicCalendar is_cal = new IslamicCalendar();
    is_cal.setCalculationType(CalculationType.ISLAMIC_CIVIL);
    is_cal.setTime(date);
    IslamicCalendar is_cal2 = new IslamicCalendar();
    is_cal2.setCalculationType(CalculationType.ISLAMIC_TBLA);
    is_cal2.setTime(date);

    int is_month = is_cal.get(Calendar.MONTH);
    int is_month2 = is_cal2.get(Calendar.MONTH);
    int is_year = is_cal.get(Calendar.YEAR);
    int is_year2 = is_cal2.get(Calendar.YEAR);
    if( (is_month != is_month2) || (is_year != is_year2))
        errln("unexpected difference between islamic and tbla month "+is_month+" : "+is_month2+" and/or year "+is_year+" : "+is_year2);
    
    int is_day = is_cal.get(Calendar.DAY_OF_MONTH);
    int is_day2 = is_cal2.get(Calendar.DAY_OF_MONTH);
    if(is_day2 - is_day != 1)
        errln("unexpected difference between civil and tbla: "+is_day2+" : "+is_day);

}
 
Example 9
Source File: DateIntervalFormatTest.java    From j2objc with Apache License 2.0 5 votes vote down vote up
private void expect(String[] data, int data_length) {
    int i = 1;
    while (i<data_length) {
        String locName = data[i++];
        ULocale loc = new ULocale(locName);
        SimpleDateFormat ref = new SimpleDateFormat(data[0], loc);
        // 'f'
        String datestr = data[i++];
        String datestr_2 = data[i++];
        Date date, date_2;
        try {
            date = ref.parse(datestr);
            date_2 = ref.parse(datestr_2);
        } catch ( ParseException e ) {
            errln("parse exception" + e);
            continue;
        }
        DateInterval dtitv = new DateInterval(date.getTime(), 
                date_2.getTime());
        String oneSkeleton = data[i++];
        DateIntervalFormat dtitvfmt = DateIntervalFormat.getInstance(
                oneSkeleton, loc);
        String expected = data[i++];
        String formatted = dtitvfmt.format(dtitv);
        if ( !formatted.equals(Utility.unescape(expected)) )  {
            errln("\"" + locName + "\\" + oneSkeleton + "\\" + datestr + "\\" + datestr_2 + "\"\t expected: " + expected +"\tgot: " + formatted + "\n");
        }
    }
}
 
Example 10
Source File: DateIntervalFormatTest.java    From j2objc with Apache License 2.0 5 votes vote down vote up
private void expectUserDII(String[] data, int data_length) {
    int i = 1;
    while (i<data_length) {
        String locName = data[i++];
        ULocale loc = new ULocale(locName);
        SimpleDateFormat ref = new SimpleDateFormat(data[0], loc);
        // 'f'
        String datestr = data[i++];
        String datestr_2 = data[i++];
        Date date, date_2;
        try {
            date = ref.parse(datestr);
            date_2 = ref.parse(datestr_2);
        } catch ( ParseException e ) {
            errln("parse exception" + e);
            continue;
        }
        DateInterval dtitv = new DateInterval(date.getTime(), 
                date_2.getTime());

        DateIntervalInfo dtitvinf = new DateIntervalInfo();
        dtitvinf.setFallbackIntervalPattern("{0} --- {1}");
        dtitvinf.setIntervalPattern("yMMMd", Calendar.MONTH, "yyyy MMM d - MMM y");
        dtitvinf.setIntervalPattern("yMMMd", Calendar.HOUR_OF_DAY, "yyyy MMM d HH:mm - HH:mm");
        DateIntervalFormat dtitvfmt = DateIntervalFormat.getInstance(
                DateFormat.YEAR_ABBR_MONTH_DAY,
                loc, dtitvinf);
        String expected = data[i++];
        String formatted = dtitvfmt.format(dtitv);
        if ( !formatted.equals(Utility.unescape(expected)) )  {
            errln("userDII: \"" + locName + "\\" + datestr + "\\" + datestr_2 + "\"\t expected: " + expected +"\tgot: " + formatted + "\n");
        }
    }
}
 
Example 11
Source File: DateFormatRegressionTest.java    From j2objc with Apache License 2.0 5 votes vote down vote up
/**
 * @bug 4104136
 */
@Test
public void Test4104136() {
    SimpleDateFormat sdf = new SimpleDateFormat();
    String pattern = "'time' hh:mm";
    sdf.applyPattern(pattern);
    logln("pattern: \"" + pattern + "\"");
    String strings[] = {"time 10:30", "time 10:x", "time 10x"};
    ParsePosition ppos[] = {new ParsePosition(10), new ParsePosition(0), new ParsePosition(0)};
    Calendar cal = Calendar.getInstance();
    cal.clear();
    cal.set(1970, Calendar.JANUARY, 1, 10, 30);
    Date dates[] = {cal.getTime(), new Date(-1), new Date(-1)};
    for (int i = 0; i < 3; i++) {
        String text = strings[i];
        ParsePosition finish = ppos[i];
        Date exp = dates[i];
        ParsePosition pos = new ParsePosition(0);
        Date d = sdf.parse(text, pos);
        logln(" text: \"" + text + "\"");
        logln(" index: %d" + pos.getIndex());
        logln(" result: " + d);
        if (pos.getIndex() != finish.getIndex())
            errln("Fail: Expected pos " + finish.getIndex());
        if (!((d == null && exp.equals(new Date(-1))) || (d.equals(exp))))
            errln( "Fail: Expected result " + exp);
    }
}
 
Example 12
Source File: DateFormatRegressionTestJ.java    From j2objc with Apache License 2.0 5 votes vote down vote up
@Test
public void Test4375399() {
    final String pattern = new String("yyyy.MM.dd G 'at' hh:mm:ss z");
    SimpleDateFormat sdf = new SimpleDateFormat(pattern, Locale.JAPAN);
    try{
        Date currentTime = sdf.parse("vggf 20  01.0 9.29 ap. J.-C. at 05:26:33 GMT+08:00",
                            new ParsePosition(0));
        if(currentTime ==null)
            logln("parse right");
    } catch(Exception e){
        errln("Error");
    }
}
 
Example 13
Source File: DateFormatRegressionTest.java    From j2objc with Apache License 2.0 4 votes vote down vote up
@Test
  public void TestT10239() {
      
      class TestDateFormatItem {
          public String parseString;
          public String pattern;
          public String expectedResult;   // null indicates expected error
          // Simple constructor
          public TestDateFormatItem(String parString, String patt, String expResult) {
              pattern = patt;
              parseString = parString;
              expectedResult = expResult;
          }
      };
      
      final TestDateFormatItem[] items = {
      //                     parse String                 pattern                 expected result
      new TestDateFormatItem("1 Oct 13 2013",             "e MMM dd yyyy",        "1 Oct 13 2013"),
      new TestDateFormatItem("02 Oct 14 2013",            "ee MMM dd yyyy",       "02 Oct 14 2013"),
      new TestDateFormatItem("Tue Oct 15 2013",           "eee MMM dd yyyy",      "Tue Oct 15 2013"),
      new TestDateFormatItem("Wednesday  Oct 16 2013",    "eeee MMM dd yyyy",     "Wednesday Oct 16 2013"),
      new TestDateFormatItem("Th Oct 17 2013",            "eeeeee MMM dd yyyy",   "Th Oct 17 2013"),
      new TestDateFormatItem("Fr Oct 18 2013",            "EEEEEE MMM dd yyyy",   "Fr Oct 18 2013"),
      new TestDateFormatItem("S Oct 19 2013",             "eeeee MMM dd yyyy",    "S Oct 19 2013"),
      new TestDateFormatItem("S Oct 20 2013",             "EEEEE MMM dd yyyy",    "S Oct 20 2013"),
      };

      StringBuffer result = new StringBuffer();
      Date d = new Date();
      Calendar cal = GregorianCalendar.getInstance(TimeZone.getTimeZone("GMT"), Locale.US); 
      SimpleDateFormat sdfmt = new SimpleDateFormat();
      ParsePosition p = new ParsePosition(0);
      for (TestDateFormatItem item: items) {
          cal.clear();
          sdfmt.setCalendar(cal);
          sdfmt.applyPattern(item.pattern);
          result.setLength(0);
          p.setIndex(0);
          p.setErrorIndex(-1);
          d = sdfmt.parse(item.parseString, p);
          if(item.expectedResult == null) {
              if(p.getErrorIndex() != -1)
                  continue;
              else
                  errln("error: unexpected parse success..."+item.parseString + " should have failed");
          }
          if(p.getErrorIndex() != -1) {
              errln("error: parse error for string " +item.parseString + " against pattern " + item.pattern + " -- idx["+p.getIndex()+"] errIdx["+p.getErrorIndex()+"]");
              continue;
          }
          cal.setTime(d);
          result = sdfmt.format(cal, result, new FieldPosition(0));
          if(!result.toString().equalsIgnoreCase(item.expectedResult)) {
              errln("error: unexpected format result. expected - " + item.expectedResult + "  but result was - " + result);
          } else {
              logln("formatted results match! - " + result.toString());
          }
      }
}
 
Example 14
Source File: DateFormatRegressionTest.java    From j2objc with Apache License 2.0 4 votes vote down vote up
/**
 * @bug 4106807
 */
@Test
public void Test4106807() {
    Date dt;
    DateFormat df = DateFormat.getDateTimeInstance();

    SimpleDateFormat sdfs[] = {
            new SimpleDateFormat("yyyyMMddHHmmss"), 
            new SimpleDateFormat("yyyyMMddHHmmss'Z'"), 
            new SimpleDateFormat("yyyyMMddHHmmss''"), 
            new SimpleDateFormat("yyyyMMddHHmmss'a''a'"), 
            new SimpleDateFormat("yyyyMMddHHmmss %")}; 
    String strings[] = {
            "19980211140000", 
            "19980211140000", 
            "19980211140000", 
            "19980211140000a", 
            "19980211140000 "}; 
    GregorianCalendar gc = new GregorianCalendar();
    TimeZone timeZone = TimeZone.getDefault();
    TimeZone gmt = (TimeZone) timeZone.clone();
    gmt.setRawOffset(0);
    for (int i = 0; i < 5; i++) {
        SimpleDateFormat format = sdfs[i];
        String dateString = strings[i];
        try {
            format.setTimeZone(gmt);
            dt = format.parse(dateString);
            // {sfb} some of these parses will fail purposely

            StringBuffer fmtd = new StringBuffer("");
            FieldPosition pos = new FieldPosition(0);
            fmtd = df.format(dt, fmtd, pos);
            logln(fmtd.toString());
            //logln(df.format(dt)); 
            gc.setTime(dt);
            logln("" + gc.get(Calendar.ZONE_OFFSET));
            StringBuffer s = new StringBuffer("");
            s = format.format(dt, s, pos);
            logln(s.toString());
        } catch (ParseException e) {
            logln("No way Jose");
        }
    }
}
 
Example 15
Source File: DateFormatRegressionTest.java    From j2objc with Apache License 2.0 4 votes vote down vote up
/**
 * @bug 4056591
 * Verify the function of the [s|g]et2DigitYearStart() API.
 */
@Test
public void Test4056591() {

    try {
        SimpleDateFormat fmt = new SimpleDateFormat("yyMMdd", Locale.US);
        Calendar cal = Calendar.getInstance();
        cal.clear();
        cal.set(1809, Calendar.DECEMBER, 25);
        Date start = cal.getTime();
        fmt.set2DigitYearStart(start);
        if ((fmt.get2DigitYearStart() != start))
            errln("get2DigitYearStart broken");
        cal.clear();
        cal.set(1809, Calendar.DECEMBER, 25);
        Date d1 = cal.getTime();
        cal.clear();
        cal.set(1909, Calendar.DECEMBER, 24);
        Date d2 = cal.getTime();
        cal.clear();
        cal.set(1809, Calendar.DECEMBER, 26);
        Date d3 = cal.getTime();
        cal.clear();
        cal.set(1861, Calendar.DECEMBER, 25);
        Date d4 = cal.getTime();
        
        Date dates[] = {d1, d2, d3, d4};

        String strings[] = {"091225", "091224", "091226", "611225"};            

        for (int i = 0; i < 4; i++) {
            String s = strings[i];
            Date exp = dates[i];
            Date got = fmt.parse(s);
            logln(s + " . " + got + "; exp " + exp);
            if (got.getTime() != exp.getTime())
                errln("set2DigitYearStart broken");
        }
    } catch (ParseException e) {
        errln("Fail: " + e);
        e.printStackTrace();
    }
}
 
Example 16
Source File: DateTimeGeneratorTest.java    From j2objc with Apache License 2.0 4 votes vote down vote up
@Test
public void TestReplacingZoneString() {
    Date testDate = new Date();
    TimeZone testTimeZone = TimeZone.getTimeZone("America/New_York");
    TimeZone bogusTimeZone = new SimpleTimeZone(1234, "Etc/Unknown");
    Calendar calendar = Calendar.getInstance();
    ParsePosition parsePosition = new ParsePosition(0);

    ULocale[] locales = ULocale.getAvailableLocales();
    int count = 0;
    for (int i = 0; i < locales.length; ++i) {
        // skip the country locales unless we are doing exhaustive tests
        if (getExhaustiveness() < 6) {
            if (locales[i].getCountry().length() > 0) {
                continue;
            }
        }
        count++;
        // Skipping some test case in the non-exhaustive mode to reduce the test time
        //ticket#6503
        if(getExhaustiveness()<=5 && count%3!=0){
            continue;
        }
        logln(locales[i].toString());
        DateTimePatternGenerator dtpgen
        = DateTimePatternGenerator.getInstance(locales[i]);

        for (int style1 = DateFormat.FULL; style1 <= DateFormat.SHORT; ++style1) {
            final SimpleDateFormat oldFormat = (SimpleDateFormat) DateFormat.getTimeInstance(style1, locales[i]);
            String pattern = oldFormat.toPattern();
            String newPattern = dtpgen.replaceFieldTypes(pattern, "VVVV"); // replaceZoneString(pattern, "VVVV");
            if (newPattern.equals(pattern)) {
                continue;
            }
            // verify that it roundtrips parsing
            SimpleDateFormat newFormat = new SimpleDateFormat(newPattern, locales[i]);
            newFormat.setTimeZone(testTimeZone);
            String formatted = newFormat.format(testDate);
            calendar.setTimeZone(bogusTimeZone);
            parsePosition.setIndex(0);
            newFormat.parse(formatted, calendar, parsePosition);
            if (parsePosition.getErrorIndex() >= 0) {
                errln("Failed parse with VVVV:\t" + locales[i] + ",\t\"" + pattern + "\",\t\"" + newPattern + "\",\t\"" + formatted.substring(0,parsePosition.getErrorIndex()) + "{}" + formatted.substring(parsePosition.getErrorIndex()) + "\"");
            } else if (!calendar.getTimeZone().getID().equals(testTimeZone.getID())) {
                errln("Failed timezone roundtrip with VVVV:\t" + locales[i] + ",\t\"" + pattern + "\",\t\"" + newPattern + "\",\t\"" + formatted + "\",\t" + calendar.getTimeZone().getID() + " != " + testTimeZone.getID());
            } else {
                logln(locales[i] + ":\t\"" + pattern + "\" => \t\"" + newPattern + "\"\t" + formatted);
            }
        }
    }
}
 
Example 17
Source File: DateIntervalFormatTest.java    From j2objc with Apache License 2.0 4 votes vote down vote up
private void expectUserCLDR(String[] data, int data_length) {
    int i = 1;
    while (i<data_length) {
        String locName = data[i++];
        ULocale loc = new ULocale(locName);
        SimpleDateFormat ref = new SimpleDateFormat(data[0], loc);
        // 'f'
        String datestr = data[i++];
        String datestr_2 = data[i++];
        Date date, date_2;
        try {
            date = ref.parse(datestr);
            date_2 = ref.parse(datestr_2);
        } catch ( ParseException e ) {
            errln("parse exception" + e);
            continue;
        }
        DateInterval dtitv = new DateInterval(date.getTime(), 
                date_2.getTime());

        DateIntervalFormat dtitvfmt = DateIntervalFormat.getInstance("yyyyMMMdd", loc);
        //DateIntervalFormat dtitvfmt = DateIntervalFormat.getInstance("yMd");
        //SimpleDateFormat dtfmt = new SimpleDateFormat("yyyy 'year' MMM 'month' dd 'day'", loc);
        //dtitvfmt.setDateFormat(dtfmt);
        DateIntervalInfo dtitvinf = new DateIntervalInfo();
        dtitvinf.setFallbackIntervalPattern("{0} --- {1}");
        dtitvinf.setIntervalPattern("yMMMd", Calendar.YEAR, "'all diff'");
        dtitvinf.setIntervalPattern("yMMMd", Calendar.MONTH, "yyyy 'diff' MMM d - MMM y");
        dtitvinf.setIntervalPattern("yMMMd", Calendar.DATE, "yyyy MMM d ~ d");
        dtitvinf.setIntervalPattern("yMMMd", Calendar.HOUR_OF_DAY, "yyyy MMMd HH:mm ~ HH:mm");
        dtitvfmt.setDateIntervalInfo(dtitvinf);
        FieldPosition pos = new FieldPosition(0);
        StringBuffer str = new StringBuffer("");
        DateFormat dtfmt = dtitvfmt.getDateFormat();
        Calendar fromCalendar = (Calendar) dtfmt.getCalendar().clone();
        Calendar toCalendar = (Calendar) dtfmt.getCalendar().clone();
        fromCalendar.setTimeInMillis(dtitv.getFromDate());
        toCalendar.setTimeInMillis(dtitv.getToDate());
        dtitvfmt.format(fromCalendar, toCalendar, str, pos);

        String expected = data[i++];
        String formatted = dtitvfmt.format(dtitv).toString();
        if ( !formatted.equals(Utility.unescape(expected)) )  {
            errln("CLDR: \"" + locName + "\\" + datestr + "\\" + datestr_2 + "\"\t expected: " + expected +"\tgot: " + formatted + "\n");
        }
    }
}
 
Example 18
Source File: DateFormatRegressionTest.java    From j2objc with Apache License 2.0 4 votes vote down vote up
/**
 * DateFormat shouldn't parse year "-1" as a two-digit year (e.g., "-1" . 1999).
 */
@Test
public void Test4182066() {
    SimpleDateFormat fmt = new SimpleDateFormat("MM/dd/yy", Locale.US);
    SimpleDateFormat dispFmt = new SimpleDateFormat("MMM dd yyyy HH:mm:ss GG", Locale.US);
    /* We expect 2-digit year formats to put 2-digit years in the right
     * window.  Out of range years, that is, anything less than "00" or
     * greater than "99", are treated as literal years.  So "1/2/3456"
     * becomes 3456 AD.  Likewise, "1/2/-3" becomes -3 AD == 2 BC.
     */
    final String STRINGS[] = 
        {"02/29/00", "01/23/01", "04/05/-1", "01/23/-9", "11/12/1314", "10/31/1", "09/12/+1", "09/12/001",}; 
    int STRINGS_COUNT = STRINGS.length;
            
    Calendar cal = Calendar.getInstance();
    Date FAIL_DATE = cal.getTime();
    cal.clear();
    cal.set(2000, Calendar.FEBRUARY, 29);
    Date d0 = cal.getTime();
    cal.clear();
    cal.set(2001, Calendar.JANUARY, 23);
    Date d1 = cal.getTime();
    cal.clear();
    cal.set(-1, Calendar.APRIL, 5);
    Date d2 = cal.getTime();
    cal.clear();
    cal.set(-9, Calendar.JANUARY, 23);
    Date d3 = cal.getTime();
    cal.clear();
    cal.set(1314, Calendar.NOVEMBER, 12);
    Date d4 = cal.getTime();
    cal.clear();
    cal.set(1, Calendar.OCTOBER, 31);
    Date d5 = cal.getTime();
    cal.clear();        
    cal.set(1, Calendar.SEPTEMBER, 12);
    Date d7 = cal.getTime();
    Date DATES[] = {d0, d1, d2, d3, d4, d5, FAIL_DATE, d7};

    String out = "";
    boolean pass = true;
    for (int i = 0; i < STRINGS_COUNT; ++i) {
        String str = STRINGS[i];
        Date expected = DATES[i];            
        Date actual = null;
        try {
            actual = fmt.parse(str);
        } catch (ParseException e) {
            actual = FAIL_DATE;
        }
        String actStr = "";
        if ((actual.getTime()) == FAIL_DATE.getTime()) {
            actStr += "null";
        } else {
            // Yuck: See j25
            actStr = ((DateFormat) dispFmt).format(actual);
        }
                           
        if (expected.getTime() == (actual.getTime())) {
            out += str + " => " + actStr + "\n";
        } else {
            String expStr = "";
            if (expected.getTime() == FAIL_DATE.getTime()) {
                expStr += "null";
            } else {
                // Yuck: See j25
                expStr = ((DateFormat) dispFmt).format(expected);
            }
            out += "FAIL: " + str + " => " + actStr + ", expected " + expStr + "\n";
            pass = false;
        }
    }
    if (pass) {
        log(out);
    } else {
        err(out);
    }
}
 
Example 19
Source File: JapaneseTest.java    From j2objc with Apache License 2.0 4 votes vote down vote up
@Test
public void Test5345parse() {
    // Test parse with incomplete information
    DateFormat fmt2= DateFormat.getDateInstance(); //DateFormat.LONG, Locale.US);
    JapaneseCalendar c = new JapaneseCalendar(TimeZone.getDefault(), new ULocale("en_US"));
    SimpleDateFormat fmt = (SimpleDateFormat)c.getDateTimeFormat(1,1,new ULocale("en_US@calendar=japanese"));
    fmt.applyPattern("G y");
    logln("fmt's locale = " + fmt.getLocale(ULocale.ACTUAL_LOCALE));
    //SimpleDateFormat fmt = new SimpleDateFormat("G y", new Locale("en_US@calendar=japanese"));
    long aDateLong = -3197117222000L; // 1868-09-08 00:00 Pacific Time (GMT-07:52:58)
    if (TimeZone.getDefaultTimeZoneType() == TimeZone.TIMEZONE_JDK) {
        // Java time zone implementation does not support LMTs
        aDateLong = -3197116800000L; // 1868-09-08 00:00 Pacific Time (GMT-08:00)
    }
    Date aDate = new Date(aDateLong);
    logln("aDate: " + aDate.toString() +", from " + aDateLong);
    String str;
    str = fmt2.format(aDate);
    logln("Test Date: " + str);
    str = fmt.format(aDate);
    logln("as Japanese Calendar: " + str);
    String expected = "Meiji 1";
    if(!str.equals(expected)) {
        errln("FAIL: Expected " + expected + " but got " + str);
    }
    Date otherDate;
    try {
        otherDate = fmt.parse(expected);
        if(!otherDate.equals(aDate)) { 
            String str3;
//            ParsePosition pp;
            Date dd = fmt.parse(expected);
            str3 = fmt.format(otherDate);
            long oLong = otherDate.getTime();
            long aLong = otherDate.getTime();
            
            errln("FAIL: Parse incorrect of " + expected + ":  wanted " + aDate + " ("+aLong+"), but got " +  " " +
                otherDate + " ("+oLong+") = " + str3 + " not " + dd.toString() );


        } else {
            logln("Parsed OK: " + expected);
        }
    } catch(java.text.ParseException pe) {
        errln("FAIL: ParseException: " + pe.toString());
        pe.printStackTrace();
    }
}
 
Example 20
Source File: JapaneseTest.java    From j2objc with Apache License 2.0 4 votes vote down vote up
@Test
public void Test3860()
{
    ULocale loc = new ULocale("ja_JP@calendar=japanese");
    Calendar cal = new JapaneseCalendar(loc);
    DateFormat enjformat = cal.getDateTimeFormat(0,0,new ULocale("en_JP@calendar=japanese"));
    DateFormat format = cal.getDateTimeFormat(0,0,loc);
    ((SimpleDateFormat)format).applyPattern("y.M.d");  // Note: just 'y' doesn't work here.
    ParsePosition pos = new ParsePosition(0);
    Date aDate = format.parse("1.1.9", pos); // after the start of heisei accession.  Jan 1, 1H wouldn't work  because it is actually showa 64
    String inEn = enjformat.format(aDate);

    cal.clear();
    cal.setTime(aDate);
    int gotYear = cal.get(Calendar.YEAR);
    int gotEra = cal.get(Calendar.ERA);
    
    int expectYear = 1;
    int expectEra = JapaneseCalendar.CURRENT_ERA;
    
    if((gotYear != expectYear) || (gotEra != expectEra)) {
        errln("Expected year " + expectYear + ", era " + expectEra +", but got year " + gotYear + " and era " + gotEra + ", == " + inEn);
    } else {
        logln("Got year " + gotYear + " and era " + gotEra + ", == " + inEn);
    }

    // Test parse with missing era (should default to current era, heisei)
    // Test parse with incomplete information
    logln("Testing parse w/ just year...");
    Calendar cal2 = new JapaneseCalendar(loc);
    SimpleDateFormat fmt = new SimpleDateFormat("y", loc);
    SimpleDateFormat fmt2 = new SimpleDateFormat("HH:mm:ss.S MMMM d, yyyy G", new ULocale("en_US@calendar=gregorian"));
    cal2.clear();
    String samplestr = "1";
    logln("Test Year: " + samplestr);
    try {
        aDate = fmt.parse(samplestr);
    } catch (ParseException pe) {
        errln("Error parsing " + samplestr);
    }
    ParsePosition pp = new ParsePosition(0);
    fmt.parse(samplestr, cal2, pp);
    logln("cal2 after 1 parse:");
    String str = fmt2.format(aDate);
    logln("as Gregorian Calendar: " + str);

    cal2.setTime(aDate);
    gotYear = cal2.get(Calendar.YEAR);
    gotEra = cal2.get(Calendar.ERA);
    expectYear = 1;
    expectEra = JapaneseCalendar.CURRENT_ERA;
    if((gotYear != 1) || (gotEra != expectEra)) {
        errln("parse "+ samplestr + " of 'y' as Japanese Calendar, expected year " + expectYear + 
            " and era " + expectEra + ", but got year " + gotYear + " and era " + gotEra + " (Gregorian:" + str +")");
    } else {            
        logln(" year: " + gotYear + ", era: " + gotEra);
    }
}