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

The following examples show how to use android.icu.text.SimpleDateFormat#format() . 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: 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 2
Source File: DateFormatRegressionTest.java    From j2objc with Apache License 2.0 6 votes vote down vote up
/**
 * @bug 4151631
 * SimpleDateFormat incorrect handling of 2 single quotes in format()
 */
@Test
public void Test4151631() {
    String pattern = 
        "'TO_DATE('''dd'-'MM'-'yyyy HH:mm:ss''' , ''DD-MM-YYYY HH:MI:SS'')'"; 
    logln("pattern=" + pattern);
    SimpleDateFormat format = new SimpleDateFormat(pattern, Locale.US);
    StringBuffer result = new StringBuffer("");
    FieldPosition pos = new FieldPosition(0);
    Calendar cal = Calendar.getInstance();
    cal.clear();
    cal.set(1998, Calendar.JUNE, 30, 13, 30, 0);
    Date d = cal.getTime();
    result = format.format(d, result, pos); 
    if (!result.toString().equals("TO_DATE('30-06-1998 13:30:00' , 'DD-MM-YYYY HH:MI:SS')")) {
        errln("Fail: result=" + result);
    } else {
        logln("Pass: result=" + result);
    }
}
 
Example 3
Source File: DateFormatRegressionTest.java    From j2objc with Apache License 2.0 6 votes vote down vote up
/**
 * @bug 4103340
 * @bug 4138203
 * This bug really only works in Locale.US, since that's what the locale
 * used for Date.toString() is.  Bug 4138203 reports that it fails on Korean
 * NT; it would actually have failed on any non-US locale.  Now it should
 * work on all locales.
 */
@Test
public void Test4103340() {

    // choose a date that is the FIRST of some month 
    // and some arbitrary time
    Calendar cal = Calendar.getInstance();
    cal.clear();
    cal.set(1997, 3, 1, 1, 1, 1);
    Date d = cal.getTime(); 
    SimpleDateFormat df = new SimpleDateFormat("MMMM", Locale.US);
    String s = d.toString();
    StringBuffer s2 = new StringBuffer("");
    FieldPosition pos = new FieldPosition(0);
    s2 = df.format(d, s2, pos);
    logln("Date=" + s); 
    logln("DF=" + s2);
    String substr = s2.substring(0,2);
    if (s.indexOf(substr) == -1)
      errln("Months should match");
}
 
Example 4
Source File: DateFormatRegressionTest.java    From j2objc with Apache License 2.0 6 votes vote down vote up
public void aux917(SimpleDateFormat fmt, String str) {

    String pat = fmt.toPattern();
    logln("==================");
    logln("testIt: pattern=" + pat + " string=" + str);
    ParsePosition pos = new ParsePosition(0);
    Object o = fmt.parseObject(str, pos);
    //logln( UnicodeString("Parsed object: ") + o );

    StringBuffer formatted = new StringBuffer("");
    FieldPosition poss = new FieldPosition(0);
    formatted = fmt.format(o, formatted, poss);

    logln("Formatted string: " + formatted);
    if (!formatted.toString().equals(str))
        errln("Fail: Want " + str + " Got " + formatted);
}
 
Example 5
Source File: DateTimeGeneratorTest.java    From j2objc with Apache License 2.0 6 votes vote down vote up
@Test
public void DayMonthTest() {
    final ULocale locale = ULocale.FRANCE;

    // set up the generator
    DateTimePatternGenerator dtpgen
    = DateTimePatternGenerator.getInstance(locale);

    // get a pattern for an abbreviated month and day
    final String pattern = dtpgen.getBestPattern("MMMd");
    SimpleDateFormat formatter = new SimpleDateFormat(pattern, locale);

    // use it to format (or parse)
    String formatted = formatter.format(new Date());
    logln("formatted=" + formatted);
    // for French, the result is "13 sept."
}
 
Example 6
Source File: CalendarRegressionTest.java    From j2objc with Apache License 2.0 5 votes vote down vote up
/**
 * Test case for ticket 9452
 * Calendar addition fall onto the missing date - 2011-12-30 in Samoa
 */
@Test
public void TestT9452() {
    TimeZone samoaTZ = TimeZone.getTimeZone("Pacific/Apia");
    GregorianCalendar cal = new GregorianCalendar(samoaTZ);

    SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ssZZZZZ");
    sdf.setTimeZone(samoaTZ);

    // Set date to 2011-12-29 00:00
    cal.clear();
    cal.set(2011, Calendar.DECEMBER, 29, 0, 0, 0);

    Date d = cal.getTime();
    String dstr = sdf.format(d);
    logln("Initial date: " + dstr);

    // Add 1 day
    cal.add(Calendar.DATE, 1);
    d = cal.getTime();
    dstr = sdf.format(d);
    logln("+1 day: " + dstr);
    assertEquals("Add 1 day", "2011-12-31T00:00:00+14:00", dstr);

    // Subtract 1 day
    cal.add(Calendar.DATE, -1);
    d = cal.getTime();
    dstr = sdf.format(d);
    logln("-1 day: " + dstr);
    assertEquals("Subtract 1 day", "2011-12-29T00:00:00-10:00", dstr);
}
 
Example 7
Source File: TimeZoneTest.java    From j2objc with Apache License 2.0 5 votes vote down vote up
@Test
public void TestDisplayName2() {
    Date now = new Date();

    String[] timezones = {"America/Chicago", "Europe/Moscow", "Europe/Rome", "Asia/Shanghai", "WET" };
    String[] locales = {"en", "fr", "de", "ja", "zh_TW", "zh_Hans" };
    for (int j = 0; j < locales.length; ++j) {
        ULocale locale = new ULocale(locales[j]);
        for (int i = 0; i < timezones.length; ++i) {
            TimeZone tz = TimeZone.getTimeZone(timezones[i]);
            String displayName0 = tz.getDisplayName(locale);
            SimpleDateFormat dt = new SimpleDateFormat("vvvv", locale);
            dt.setTimeZone(tz);
            String displayName1 = dt.format(now);  // date value _does_ matter if we fallback to GMT
            logln(locale.getDisplayName() + ", " + tz.getID() + ": " + displayName0);
            if (!displayName1.equals(displayName0)) {
                // This could happen when the date used is in DST,
                // because TimeZone.getDisplayName(ULocale) may use
                // localized GMT format for the time zone's standard
                // time.
                if (tz.inDaylightTime(now)) {
                    // Try getDisplayName with daylight argument
                    displayName0 = tz.getDisplayName(true, TimeZone.LONG_GENERIC, locale);
                }
                if (!displayName1.equals(displayName0)) {
                    errln(locale.getDisplayName() + ", " + tz.getID() + 
                            ": expected " + displayName1 + " but got: " + displayName0);
                }
            }
        }
    }
}
 
Example 8
Source File: TimeZoneRegressionTest.java    From j2objc with Apache License 2.0 5 votes vote down vote up
/**
 * Test to see if DateFormat understands zone equivalency groups.  It
 * might seem that this should be a DateFormat test, but it's really a
 * TimeZone test -- the changes to DateFormat are minor.
 *
 * We use two known, zones that are equivalent, where one zone has
 * localized name data, and the other doesn't, in some locale.
 */
@Test
public void TestJ449() {
    // not used String str;

    // Modify the following three as necessary.  The two IDs must
    // specify two zones in the same equivalency group.  One must have
    // locale data in 'loc'; the other must not.
    String idWithLocaleData = "America/Los_Angeles";
    String idWithoutLocaleData = "PST"; // "US/Pacific";
    Locale loc = new Locale("en", "", "");

    TimeZone zoneWith = TimeZone.getTimeZone(idWithLocaleData);
    TimeZone zoneWithout = TimeZone.getTimeZone(idWithoutLocaleData);
    // Make sure we got valid zones
    if (!(zoneWith.getID().equals(idWithLocaleData) &&
          zoneWithout.getID().equals(idWithoutLocaleData))) {
        warnln("Fail: Unable to create zones");
    } else {
        GregorianCalendar calWith = new GregorianCalendar(zoneWith);
        GregorianCalendar calWithout = new GregorianCalendar(zoneWithout);
        SimpleDateFormat fmt =
            new SimpleDateFormat("MMM d yyyy hh:mm a zzz", loc);
        Date date = new Date(0L);
        fmt.setCalendar(calWith);
        String strWith = fmt.format(date);
        fmt.setCalendar(calWithout);
        String strWithout = fmt.format(date);
        if (strWith.equals(strWithout)) {
            logln("Ok: " + idWithLocaleData + " -> " +
                  strWith + "; " + idWithoutLocaleData + " -> " +
                  strWithout);
        } else {
            errln("FAIL: " + idWithLocaleData + " -> " +
                  strWith + "; " + idWithoutLocaleData + " -> " +
                  strWithout);
        }
    }
}
 
Example 9
Source File: JapaneseTest.java    From j2objc with Apache License 2.0 5 votes vote down vote up
@Test
public void TestJapaneseYear3282() {
    Calendar c = Calendar.getInstance(ULocale.ENGLISH);
    c.set(2003,Calendar.SEPTEMBER,25);
    JapaneseCalendar jcal = new JapaneseCalendar();
    //jcal.setTime(new Date(1187906308151L));  alternate value
    jcal.setTime(c.getTime());
    logln("Now is: " + jcal.getTime());
    c.setTime(jcal.getTime());
    int nowYear = c.get(Calendar.YEAR);
    logln("Now year: "+nowYear);
    SimpleDateFormat jdf = (SimpleDateFormat) SimpleDateFormat.getDateInstance(jcal,
            SimpleDateFormat.DEFAULT, Locale.getDefault());
    jdf.applyPattern("G yy/MM/dd");
    String text = jdf.format(jcal.getTime());
    logln("Now is: " + text + " (in Japan)");
    try {
        Date date = jdf.parse(text);
        logln("But is this not the date?: " + date);
        c.setTime(date);
        int thenYear = c.get(Calendar.YEAR);
        logln("Then year: "+thenYear);
        if(thenYear != nowYear) {
            errln("Nowyear "+nowYear +" is not thenyear "+thenYear);
        } else {
            logln("Nowyear "+nowYear +" == thenyear "+thenYear);
        }
    } catch (java.text.ParseException ex) {
        ex.printStackTrace();
    }
}
 
Example 10
Source File: DateFormatRegressionTest.java    From j2objc with Apache License 2.0 5 votes vote down vote up
/**
 * @bug 4101483
 */
@Test
public void Test4101483() {
    SimpleDateFormat sdf = new SimpleDateFormat("z", Locale.US);
    FieldPosition fp = new FieldPosition(DateFormat.TIMEZONE_FIELD);
    Date d = new Date(9234567890L);
    StringBuffer buf = new StringBuffer("");
    sdf.format(d, buf, fp);
    logln(sdf.format(d, buf, fp).toString());
    logln("beginIndex = " + fp.getBeginIndex());
    logln("endIndex = " + fp.getEndIndex());
    if (fp.getBeginIndex() == fp.getEndIndex())
        errln("Fail: Empty field");
}
 
Example 11
Source File: TimeZoneRegressionTest.java    From j2objc with Apache License 2.0 4 votes vote down vote up
boolean checkCalendar314(GregorianCalendar testCal, TimeZone testTZ) {
    // GregorianCalendar testCal = (GregorianCalendar)aCal.clone();

    final int ONE_DAY = 24*60*60*1000;

    int tzOffset, tzRawOffset;
    Float tzOffsetFloat,tzRawOffsetFloat;
    // Here is where the user made an error.  They were passing in the value of
    // the MILLSECOND field; you need to pass in the millis in the day in STANDARD
    // time.
    int millis = testCal.get(Calendar.MILLISECOND) +
        1000 * (testCal.get(Calendar.SECOND) +
                60 * (testCal.get(Calendar.MINUTE) +
                      60 * (testCal.get(Calendar.HOUR_OF_DAY)))) -
        testCal.get(Calendar.DST_OFFSET);

    /* Fix up millis to be in range.  ASSUME THAT WE ARE NOT AT THE
     * BEGINNING OR END OF A MONTH.  We must add this code because
     * getOffset() has been changed to be more strict about the parameters
     * it receives -- it turns out that this test was passing in illegal
     * values. */
    int date = testCal.get(Calendar.DATE);
    int dow  = testCal.get(Calendar.DAY_OF_WEEK);
    while (millis < 0) {
        millis += ONE_DAY;
        --date;
        dow = Calendar.SUNDAY + ((dow - Calendar.SUNDAY + 6) % 7);
    }
    while (millis >= ONE_DAY) {
        millis -= ONE_DAY;
        ++date;
        dow = Calendar.SUNDAY + ((dow - Calendar.SUNDAY + 1) % 7);
    }

    tzOffset = testTZ.getOffset(testCal.get(Calendar.ERA),
                                testCal.get(Calendar.YEAR),
                                testCal.get(Calendar.MONTH),
                                date,
                                dow,
                                millis);
    tzRawOffset = testTZ.getRawOffset();
    tzOffsetFloat = new Float((float)tzOffset/(float)3600000);
    tzRawOffsetFloat = new Float((float)tzRawOffset/(float)3600000);

    Date testDate = testCal.getTime();

    boolean inDaylightTime = testTZ.inDaylightTime(testDate);
    SimpleDateFormat sdf = new SimpleDateFormat("MM/dd/yyyy HH:mm");
    sdf.setCalendar(testCal);
    String inDaylightTimeString;

    boolean passed;

    if (inDaylightTime)
    {
        inDaylightTimeString = " DST ";
        passed = (tzOffset == (tzRawOffset + 3600000));
    }
    else
    {
        inDaylightTimeString = "     ";
        passed = (tzOffset == tzRawOffset);
    }

    String output = testTZ.getID() + " " + sdf.format(testDate) +
        " Offset(" + tzOffsetFloat + ")" +
        " RawOffset(" + tzRawOffsetFloat + ")" +
        " " + millis/(float)3600000 + " " +
        inDaylightTimeString;

    if (passed)
        output += "     ";
    else
        output += "ERROR";

    if (passed) logln(output); else errln(output);
    return passed;
}
 
Example 12
Source File: TimeZoneRegressionTest.java    From j2objc with Apache License 2.0 4 votes vote down vote up
/**
 * TimeZone broken at midnight.  The TimeZone code fails to handle
 * transitions at midnight correctly.
 */
@Test
public void Test4162593() {
    SimpleDateFormat fmt = new SimpleDateFormat("z", Locale.US);
    final int ONE_HOUR = 60*60*1000;
    final float H = (float) ONE_HOUR;
    TimeZone initialZone = TimeZone.getDefault();
    SimpleDateFormat sdf = new SimpleDateFormat("MMM dd yyyy HH:mm z");

    SimpleTimeZone asuncion = new SimpleTimeZone(-4*ONE_HOUR, "America/Asuncion" /*PY%sT*/,
        Calendar.OCTOBER, 1, 0 /*DOM*/, 0*ONE_HOUR,
        Calendar.MARCH, 1, 0 /*DOM*/, 0*ONE_HOUR, 1*ONE_HOUR);

    /* Zone
     * Starting time
     * Transition expected between start+1H and start+2H
     */
    Object[] DATA = {
        new SimpleTimeZone(2*ONE_HOUR, "Asia/Damascus" /*EE%sT*/,
            Calendar.APRIL, 1, 0 /*DOM*/, 0*ONE_HOUR,
            Calendar.OCTOBER, 1, 0 /*DOM*/, 0*ONE_HOUR, 1*ONE_HOUR),
        new int[] {1998, Calendar.SEPTEMBER, 30, 22, 0},
        Boolean.TRUE,

        asuncion,
        new int[] {2000, Calendar.FEBRUARY, 28, 22, 0},
        Boolean.FALSE,

        asuncion,
        new int[] {2000, Calendar.FEBRUARY, 29, 22, 0},
        Boolean.TRUE,
    };

    String[] zone = new String[4];

    for (int j=0; j<DATA.length; j+=3) {
        TimeZone tz = (TimeZone)DATA[j];
        TimeZone.setDefault(tz);
        fmt.setTimeZone(tz);
        sdf.setTimeZone(tz);

        // Must construct the Date object AFTER setting the default zone
        int[] p = (int[])DATA[j+1];
        Calendar cal = Calendar.getInstance();
        cal.clear();
        cal.set(p[0], p[1], p[2], p[3], p[4]);
        long start = cal.getTime().getTime();
        boolean transitionExpected = ((Boolean)DATA[j+2]).booleanValue();

        logln(tz.getID() + ":");
        for (int i=0; i<4; ++i) {
            Date d = new Date(start + i*ONE_HOUR);
            zone[i] = fmt.format(d);
            logln("" + i + ": " + sdf.format(d) + " => " + zone[i] +
                  " (" + d.getTime()/H + ")");
        }
        cal.set(p[0], p[1], p[2], 0, 0);
        for (int i=0; i<4; ++i) {
            int h = 22+i;
            int dom = p[2]+(h>=24?1:0);
            h %= 24;
            int ms = h*ONE_HOUR;
            cal.clear();
            cal.set(p[0], p[1], dom, 0, 0);
            int off = tz.getOffset(GregorianCalendar.AD,
                                   cal.get(Calendar.YEAR),
                                   cal.get(Calendar.MONTH),
                                   cal.get(Calendar.DATE),
                                   cal.get(Calendar.DAY_OF_WEEK),
                                   ms);
            cal.add(Calendar.HOUR, h);
            int dstOffset = cal.get(Calendar.DST_OFFSET);
            logln("h=" + h + "; dom=" + dom +
                  "; ZONE_OFFSET=" + cal.get(Calendar.ZONE_OFFSET)/H +
                  "; DST_OFFSET=" + dstOffset/H +
                  "; getOffset()=" + off/H +
                  " (" + cal.getTime().getTime()/H + ")");
        }
        if (zone[0].equals(zone[1]) &&
            (zone[1].equals(zone[2]) != transitionExpected) &&
            zone[2].equals(zone[3])) {
            logln("Ok: transition " + transitionExpected);
        } else {
            errln("FAIL: expected " +
                  (transitionExpected?"transition":"no transition"));
        }
    }

// restore the initial time zone so that this test case
// doesn't affect the others.
TimeZone.setDefault(initialZone);
}
 
Example 13
Source File: DateFormatRegressionTest.java    From j2objc with Apache License 2.0 4 votes vote down vote up
@Test
public void Test_GEec() {
    class PatternAndResult {
        private String pattern;
        private String result;
        PatternAndResult(String pat, String res) {
            pattern = pat;
            result = res;
        }
        public String getPattern()  { return pattern; }
        public String getResult()  { return result; }
    }
    final PatternAndResult[] tests = {
        new PatternAndResult( "dd MMM yyyy GGG",   "02 Jul 2008 AD" ),
        new PatternAndResult( "dd MMM yyyy GGGGG", "02 Jul 2008 A" ),
        new PatternAndResult( "e dd MMM yyyy",     "4 02 Jul 2008" ),
        new PatternAndResult( "ee dd MMM yyyy",    "04 02 Jul 2008" ),
        new PatternAndResult( "c dd MMM yyyy",     "4 02 Jul 2008" ),
        new PatternAndResult( "cc dd MMM yyyy",    "4 02 Jul 2008" ),
        new PatternAndResult( "eee dd MMM yyyy",   "Wed 02 Jul 2008" ),
        new PatternAndResult( "EEE dd MMM yyyy",   "Wed 02 Jul 2008" ),
        new PatternAndResult( "EE dd MMM yyyy",    "Wed 02 Jul 2008" ),
        new PatternAndResult( "eeee dd MMM yyyy",  "Wednesday 02 Jul 2008" ),
        new PatternAndResult( "eeeee dd MMM yyyy", "W 02 Jul 2008" ),
        new PatternAndResult( "e ww YYYY",         "4 27 2008" ),
        new PatternAndResult( "c ww YYYY",         "4 27 2008" ),
    };
    ULocale loc = ULocale.ENGLISH;
    TimeZone tz = TimeZone.getTimeZone("America/Los_Angeles");
    Calendar cal = new GregorianCalendar(tz, loc);
    SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MMM-dd", loc);
    for ( int i = 0; i < tests.length; i++ ) {
        PatternAndResult item = tests[i];
        dateFormat.applyPattern( item.getPattern() );
        cal.set(2008, 6, 2, 5, 0); // 2008 July 02 5 AM PDT
        StringBuffer buf = new StringBuffer(32);
        FieldPosition fp = new FieldPosition(DateFormat.YEAR_FIELD);
        dateFormat.format(cal, buf, fp);
        if ( buf.toString().compareTo(item.getResult()) != 0 ) {
            errln("for pattern " + item.getPattern() + ", expected " + item.getResult() + ", got " + buf );
        }
        ParsePosition pos = new ParsePosition(0);
        dateFormat.parse( item.getResult(), cal, pos);
        int year = cal.get(Calendar.YEAR);
        int month = cal.get(Calendar.MONTH);
        int day = cal.get(Calendar.DATE);
        if ( year != 2008 || month != 6 || day != 2 ) {
            errln("use pattern " + item.getPattern() + " to parse " + item.getResult() +
                    ", expected y2008 m6 d2, got " + year + " " + month + " " + day );
        }
    }
}
 
Example 14
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 15
Source File: DateFormatRegressionTest.java    From j2objc with Apache License 2.0 4 votes vote down vote up
@Test
  public void TestT10619() {
      
      class TestDateFormatLeniencyItem {
          public boolean leniency;
          public String parseString;
          public String pattern;
          public String expectedResult;   // null indicates expected error
           // Simple constructor
          public TestDateFormatLeniencyItem(boolean len, String parString, String patt, String expResult) {
              leniency = len;
              pattern = patt;
              parseString = parString;
              expectedResult = expResult;
          }
      };

      final TestDateFormatLeniencyItem[] items = {
          //                             leniency    parse String       pattern                 expected result
          new TestDateFormatLeniencyItem(true,       "2008-Jan 02",     "yyyy-LLL. dd",         "2008-Jan. 02"),
          new TestDateFormatLeniencyItem(false,      "2008-Jan 03",     "yyyy-LLL. dd",         null),
          new TestDateFormatLeniencyItem(true,       "2008-Jan--04",    "yyyy-MMM' -- 'dd",     "2008-Jan -- 04"),
          new TestDateFormatLeniencyItem(false,      "2008-Jan--05",    "yyyy-MMM' -- 'dd",     null),
          new TestDateFormatLeniencyItem(true,       "2008-12-31",      "yyyy-mm-dd",           "2008-12-31"),
          new TestDateFormatLeniencyItem(false,      "6 Jan 05 2008",   "eee MMM dd yyyy",      null),
          new TestDateFormatLeniencyItem(true,       "6 Jan 05 2008",   "eee MMM dd yyyy",      "Sat Jan 05 2008"),
      };

      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 (TestDateFormatLeniencyItem item: items) {
          cal.clear();
          sdfmt.setCalendar(cal);
          sdfmt.applyPattern(item.pattern);
          sdfmt.setLenient(item.leniency);
          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 + " w/ lenient="+item.leniency+" should have failed");
          }
          if(p.getErrorIndex() != -1) {
              errln("error: parse error for string " +item.parseString + " -- 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 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: 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 18
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);
    }
}
 
Example 19
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 20
Source File: GlobalizationPreferences.java    From j2objc with Apache License 2.0 4 votes vote down vote up
/**
 * Get the display name for an ID: language, script, territory, currency, timezone...
 * Uses the language priority list to do so.
 *
 * @param id language code, script code, ...
 * @param type specifies the type of the ID: ID_LANGUAGE, etc.
 * @return the display name
 * @hide draft / provisional / internal are hidden on Android
 */
public String getDisplayName(String id, int type) {
    String result = id;
    for (ULocale locale : getLocales()) {
        if (!isAvailableLocale(locale, TYPE_GENERIC)) {
            continue;
        }
        switch (type) {
        case ID_LOCALE:
            result = ULocale.getDisplayName(id, locale);
            break;
        case ID_LANGUAGE:
            result = ULocale.getDisplayLanguage(id, locale);
            break;
        case ID_SCRIPT:
            result = ULocale.getDisplayScript("und-" + id, locale);
            break;
        case ID_TERRITORY:
            result = ULocale.getDisplayCountry("und-" + id, locale);
            break;
        case ID_VARIANT:
            // TODO fix variant parsing
            result = ULocale.getDisplayVariant("und-QQ-" + id, locale);
            break;
        case ID_KEYWORD:
            result = ULocale.getDisplayKeyword(id, locale);
            break;
        case ID_KEYWORD_VALUE:
            String[] parts = new String[2];
            Utility.split(id,'=',parts);
            result = ULocale.getDisplayKeywordValue("und@"+id, parts[0], locale);
            // TODO fix to tell when successful
            if (result.equals(parts[1])) {
                continue;
            }
            break;
        case ID_CURRENCY_SYMBOL:
        case ID_CURRENCY:
            Currency temp = new Currency(id);
            result =temp.getName(locale, type==ID_CURRENCY
                                 ? Currency.LONG_NAME
                                 : Currency.SYMBOL_NAME, new boolean[1]);
            // TODO: have method that doesn't take parameter. Add
            // function to determine whether string is choice
            // format.
            // TODO: have method that doesn't require us
            // to create a currency
            break;
        case ID_TIMEZONE:
            SimpleDateFormat dtf = new SimpleDateFormat("vvvv",locale);
            dtf.setTimeZone(TimeZone.getFrozenTimeZone(id));
            result = dtf.format(new Date());
            // TODO, have method that doesn't require us to create a timezone
            // fix other hacks
            // hack for couldn't match

            boolean isBadStr = false;
            // Matcher badTimeZone = Pattern.compile("[A-Z]{2}|.*\\s\\([A-Z]{2}\\)").matcher("");
            // badtzstr = badTimeZone.reset(result).matches();
            String teststr = result;
            int sidx = result.indexOf('(');
            int eidx = result.indexOf(')');
            if (sidx != -1 && eidx != -1 && (eidx - sidx) == 3) {
                teststr = result.substring(sidx+1, eidx);
            }
            if (teststr.length() == 2) {
                isBadStr = true;
                for (int i = 0; i < 2; i++) {
                    char c = teststr.charAt(i);
                    if (c < 'A' || 'Z' < c) {
                        isBadStr = false;
                        break;
                    }
                }
            }
            if (isBadStr) {
                continue;
            }
            break;
        default:
            throw new IllegalArgumentException("Unknown type: " + type);
        }

        // TODO need better way of seeing if we fell back to root!!
        // This will not work at all for lots of stuff
        if (!id.equals(result)) {
            return result;
        }
    }
    return result;
}