Java Code Examples for android.icu.util.Calendar#setTime()

The following examples show how to use android.icu.util.Calendar#setTime() . 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: 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 2
Source File: CompatibilityTest.java    From j2objc with Apache License 2.0 6 votes vote down vote up
@Test
public void TestEpochStartFields() {
    TimeZone z = TimeZone.getDefault();
    Calendar c = Calendar.getInstance();
    Date d = new Date(-z.getRawOffset());
    if (z.inDaylightTime(d)) {
        logln("Warning: Skipping test because " + d +
              " is in DST.");
    }
    else {
        c.setTime(d);
        c.setMinimalDaysInFirstWeek(1);
        for (int i=0; i<Calendar.ZONE_OFFSET; ++i) {
            if (c.get(i) != EPOCH_FIELDS[i])
                errln("Expected field " + i + " to have value " + EPOCH_FIELDS[i] +
                      "; saw " + c.get(i) + " instead");
        }
        if (c.get(Calendar.ZONE_OFFSET) != z.getRawOffset())
            errln("Expected field ZONE_OFFSET to have value " + z.getRawOffset() +
                  "; saw " + c.get(Calendar.ZONE_OFFSET) + " instead");
        if (c.get(Calendar.DST_OFFSET) != 0)
            errln("Expected field DST_OFFSET to have value 0" +
                  "; saw " + c.get(Calendar.DST_OFFSET) + " instead");
    }
}
 
Example 3
Source File: HolidayTest.java    From j2objc with Apache License 2.0 6 votes vote down vote up
@Test
public void TestEaster(){        
    // Verify that Easter is working. Should be April 20, 2014
    final Holiday h = new EasterHoliday("Easter Sunday");
    final Date beginApril = getDate(2014, Calendar.APRIL, 1);
    final Date endApril   = getDate(2014, Calendar.APRIL, 30);
    final Date expect     = getDate(2014, Calendar.APRIL, 20);
    final Date actual     = h.firstBetween(beginApril, endApril);
    
    if(actual == null) {
        errln("Error: Easter 2014 should be on " + expect + " but got null.");
    } else {
        Calendar c = Calendar.getInstance(TimeZone.GMT_ZONE, Locale.US);
        c.setTime(actual);
        assertEquals("Easter's year:  ", 2014, c.get(Calendar.YEAR));
        assertEquals("Easter's month: ", Calendar.APRIL, c.get(Calendar.MONTH));
        assertEquals("Easter's date:  ", 20, c.get(Calendar.DATE));
    }
}
 
Example 4
Source File: CompatibilityTest.java    From j2objc with Apache License 2.0 5 votes vote down vote up
@Test
public void TestAddSetOrder621() {
    java.util.Calendar tempcal = java.util.Calendar.getInstance();
    tempcal.clear();
    tempcal.set(1997, 4, 14, 13, 23, 45);
    Date d = tempcal.getTime();

    Calendar cal = Calendar.getInstance ();
    cal.setTime (d);
    cal.add (Calendar.DATE, -5);
    cal.set (Calendar.HOUR_OF_DAY, 0);
    cal.set (Calendar.MINUTE, 0);
    cal.set (Calendar.SECOND, 0);
    // ma feb 03 00:00:00 GMT+00:00 1997
    String s = cal.getTime ().toString ();

    cal = Calendar.getInstance ();
    cal.setTime (d);
    cal.set (Calendar.HOUR_OF_DAY, 0);
    cal.set (Calendar.MINUTE, 0);
    cal.set (Calendar.SECOND, 0);
    cal.add (Calendar.DATE, -5);
    // ma feb 03 13:11:06 GMT+00:00 1997
    String s2 = cal.getTime ().toString ();

    if (s.equals(s2))
        logln("Pass: " + s + " == " + s2);
    else
        errln("FAIL: " + s + " != " + s2);
}
 
Example 5
Source File: IBMCalendarTest.java    From j2objc with Apache License 2.0 5 votes vote down vote up
/**
 * Test behavior of fieldDifference around leap years.  Also test a large
 * field difference to check binary search.
 */
@Test
public void TestLeapFieldDifference() {
    Calendar cal = Calendar.getInstance();
    cal.set(2004, Calendar.FEBRUARY, 29);
    Date date2004 = cal.getTime();
    cal.set(2000, Calendar.FEBRUARY, 29);
    Date date2000 = cal.getTime();
    int y = cal.fieldDifference(date2004, Calendar.YEAR);
    int d = cal.fieldDifference(date2004, Calendar.DAY_OF_YEAR);
    if (d == 0) {
        logln("Ok: 2004/Feb/29 - 2000/Feb/29 = " + y + " years, " + d + " days");
    } else {
        errln("FAIL: 2004/Feb/29 - 2000/Feb/29 = " + y + " years, " + d + " days");
    }
    cal.setTime(date2004);
    y = cal.fieldDifference(date2000, Calendar.YEAR);
    d = cal.fieldDifference(date2000, Calendar.DAY_OF_YEAR);
    if (d == 0) {
        logln("Ok: 2000/Feb/29 - 2004/Feb/29 = " + y + " years, " + d + " days");
    } else {
        errln("FAIL: 2000/Feb/29 - 2004/Feb/29 = " + y + " years, " + d + " days");
    }
    // Test large difference
    cal.set(2001, Calendar.APRIL, 5); // 2452005
    Date ayl = cal.getTime();
    cal.set(1964, Calendar.SEPTEMBER, 7); // 2438646
    Date asl = cal.getTime();
    d = cal.fieldDifference(ayl, Calendar.DAY_OF_MONTH);
    cal.setTime(ayl);
    int d2 = cal.fieldDifference(asl, Calendar.DAY_OF_MONTH);
    if (d == -d2 && d == 13359) {
        logln("Ok: large field difference symmetrical " + d);
    } else {
        logln("FAIL: large field difference incorrect " + d + ", " + d2 +
              ", expect +/- 13359");
    }
}
 
Example 6
Source File: CalendarRegressionTest.java    From j2objc with Apache License 2.0 5 votes vote down vote up
@Test
public void Test4070502() {
    java.util.Calendar tempcal = java.util.Calendar.getInstance();
    tempcal.clear();
    tempcal.set(1998, 0, 30);
    Date d = getAssociatedDate(tempcal.getTime());
    Calendar cal = new GregorianCalendar();
    cal.setTime(d);
    if (cal.get(Calendar.DAY_OF_WEEK) == Calendar.SATURDAY ||
        cal.get(Calendar.DAY_OF_WEEK) == Calendar.SUNDAY)
        errln("Fail: Want weekday Got " + d);
}
 
Example 7
Source File: TimeZoneBoundaryTest.java    From j2objc with Apache License 2.0 5 votes vote down vote up
/**
 * Check that the given year/month/dom/hour maps to and from the
 * given epochHours.  This verifies the functioning of the
 * calendar and time zone in conjunction with one another,
 * including the calendar time->fields and fields->time and
 * the time zone getOffset method.
 *
 * @param epochHours hours after Jan 1 1970 0:00 GMT.
 */
void verifyMapping(Calendar cal, int year, int month, int dom, int hour,
                   double epochHours) {
    double H = 3600000.0;
    cal.clear();
    cal.set(year, month, dom, hour, 0, 0);
    Date d = cal.getTime();
    double e = d.getTime() / H;
    Date ed = new Date((long)(epochHours * H));
    if (e == epochHours) {
        logln("Ok: " + year + "/" + (month+1) + "/" + dom + " " + hour + ":00 => " +
              e + " (" + ed + ")");
    } else {
        errln("FAIL: " + year + "/" + (month+1) + "/" + dom + " " + hour + ":00 => " +
              e + " (" + new Date((long)(e * H)) + ")" +
              ", expected " + epochHours + " (" + ed + ")");
    }
    cal.setTime(ed);
    if (cal.get(Calendar.YEAR) == year &&
        cal.get(Calendar.MONTH) == month &&
        cal.get(Calendar.DATE) == dom &&
        cal.get(Calendar.MILLISECONDS_IN_DAY) == hour * 3600000) {
        logln("Ok: " + epochHours + " (" + ed + ") => " +
              cal.get(Calendar.YEAR) + "/" +
              (cal.get(Calendar.MONTH)+1) + "/" +
              cal.get(Calendar.DATE) + " " +
              cal.get(Calendar.MILLISECONDS_IN_DAY)/H);
    } else {
        errln("FAIL: " + epochHours + " (" + ed + ") => " +
              cal.get(Calendar.YEAR) + "/" +
              (cal.get(Calendar.MONTH)+1) + "/" +
              cal.get(Calendar.DATE) + " " +
              cal.get(Calendar.MILLISECONDS_IN_DAY)/H +
              ", expected " + year + "/" + (month+1) + "/" + dom +
              " " + hour);
    }
}
 
Example 8
Source File: CompatibilityTest.java    From j2objc with Apache License 2.0 5 votes vote down vote up
@Test
public void TestSecondsZero121() {
    Calendar        cal = new GregorianCalendar();
    // Initialize with current date/time
    cal.setTime(new Date());
    // Round down to minute
    cal.set(Calendar.SECOND, 0);
    Date    d = cal.getTime();
    String s = d.toString();
    if (s.indexOf(":00 ") < 0) errln("Expected to see :00 in " + s);
}
 
Example 9
Source File: CalendarViewLegacyDelegate.java    From android_9.0.0_r45 with Apache License 2.0 5 votes vote down vote up
public boolean getBoundsForDate(Calendar date, Rect outBounds) {
    Calendar currDay = Calendar.getInstance();
    currDay.setTime(mFirstDay.getTime());
    for (int i = 0; i < mDaysPerWeek; i++) {
        if ((date.get(Calendar.YEAR) == currDay.get(Calendar.YEAR))
            && (date.get(Calendar.MONTH) == currDay.get(Calendar.MONTH))
            && (date.get(Calendar.DAY_OF_MONTH) == currDay.get(Calendar.DAY_OF_MONTH))) {
            // We found the matching date. Follow the logic in the draw pass that divides
            // the available horizontal space equally between all the entries in this week.
            // Note that if we're showing week number, the start entry will be that number.
            int cellSize = mWidth / mNumCells;
            if (isLayoutRtl()) {
                outBounds.left = cellSize *
                        (mShowWeekNumber ? (mNumCells - i - 2) : (mNumCells - i - 1));
            } else {
                outBounds.left = cellSize * (mShowWeekNumber ? i + 1 : i);
            }
            outBounds.top = 0;
            outBounds.right = outBounds.left + cellSize;
            outBounds.bottom = getHeight();
            return true;
        }
        // Add one day
        currDay.add(Calendar.DAY_OF_MONTH, 1);
    }
    return false;
}
 
Example 10
Source File: CompatibilityTest.java    From j2objc with Apache License 2.0 5 votes vote down vote up
void aux4064654(int yr, int mo, int dt, int hr, int mn, int sc) {
    Date date;
    Calendar gmtcal = Calendar.getInstance();
    gmtcal.setTimeZone(TimeZone.getTimeZone("Africa/Casablanca"));
    gmtcal.set(yr, mo-1, dt, hr, mn, sc);
    gmtcal.set(Calendar.MILLISECOND, 0);

    date = gmtcal.getTime();
    logln("date = "+date);

    Calendar cal = Calendar.getInstance();
    cal.setTimeZone(TimeZone.getTimeZone("America/Los_Angels"));
    cal.setTime(date);

    int offset = cal.getTimeZone().getOffset(cal.get(Calendar.ERA),
                                             cal.get(Calendar.YEAR),
                                             cal.get(Calendar.MONTH),
                                             cal.get(Calendar.DATE),
                                             cal.get(Calendar.DAY_OF_WEEK),
                                             cal.get(Calendar.MILLISECOND));

    logln("offset for "+date+"= "+(offset/1000/60/60.0) + "hr");

    int utc = ((cal.get(Calendar.HOUR_OF_DAY) * 60 +
                cal.get(Calendar.MINUTE)) * 60 +
               cal.get(Calendar.SECOND)) * 1000 +
        cal.get(Calendar.MILLISECOND) - offset;

    int expected = ((hr * 60 + mn) * 60 + sc) * 1000;

    if (utc != expected)
        errln("FAIL: Discrepancy of " +
              (utc - expected) + " millis = " +
              ((utc-expected)/1000/60/60.0) + " hr");
}
 
Example 11
Source File: LocaleAliasTest.java    From j2objc with Apache License 2.0 5 votes vote down vote up
@Test
public void TestCalendar() {
    ULocale defLoc = ULocale.getDefault();
    ULocale.setDefault(_DEFAULT_LOCALE);
    for (int i=0; i<_LOCALE_NUMBER; i++) {
        ULocale oldLoc = _LOCALES[i][0];
        ULocale newLoc = _LOCALES[i][1];
        if(availableMap.get(_LOCALES[i][1])==null){
            logln(_LOCALES[i][1]+" is not available. Skipping!");
            continue;
        }
        Calendar c1 = Calendar.getInstance(oldLoc);
        Calendar c2 = Calendar.getInstance(newLoc);
        c1.setTime(c2.getTime());
        //Test function "getFirstDayOfWeek"
//        int firstDayOfWeek1 = c1.getFirstDayOfWeek();
//        int firstDayOfWeek2 = c2.getFirstDayOfWeek();
//        if (firstDayOfWeek1 != firstDayOfWeek2) {
//            this.logln("Calendar(getFirstDayOfWeek) old:"
//                    +firstDayOfWeek1+"   new:"+firstDayOfWeek2);
//            pass = false;
//        }
                
        //Test function "getLocale(ULocale.VALID_LOCALE)"
        ULocale l1 = c1.getLocale(ULocale.VALID_LOCALE);
        ULocale l2 = c2.getLocale(ULocale.VALID_LOCALE);
        if (!newLoc.equals(l1)) {
            errln("CalendarTest: newLoc!=l1: newLoc= "+newLoc +" l1= "+l1);
        }
        if (!l1.equals(l2)) {
            errln("CalendarTest: l1!=l2: l1= "+l1 +" l2= "+l2);
        }
        if(!c1.equals(c2)){
            errln("CalendarTest: c1!=c2.  newLoc= "+newLoc +" oldLoc= "+oldLoc);
        }
        logln("Calendar(getLocale) old:"+l1+"   new:"+l2);    
    }
    ULocale.setDefault(defLoc);
}
 
Example 12
Source File: RelativeDateFormat.java    From j2objc with Apache License 2.0 5 votes vote down vote up
/**
 * @return the number of days in "until-now"
 */
private static int dayDifference(Calendar until) {
    Calendar nowCal = (Calendar)until.clone();
    Date nowDate = new Date(System.currentTimeMillis());
    nowCal.clear();
    nowCal.setTime(nowDate);
    int dayDiff = until.get(Calendar.JULIAN_DAY) - nowCal.get(Calendar.JULIAN_DAY);
    return dayDiff;
}
 
Example 13
Source File: TimeZoneRegressionTest.java    From j2objc with Apache License 2.0 5 votes vote down vote up
/**
 * CANNOT REPRODUDE
 *
 * Yet another _alleged_ bug in TimeZone.getOffset(), a method that never
 * should have been made public.  It's simply too hard to use correctly.
 *
 * The original test code failed to do the following:
 * (1) Call Calendar.setTime() before getting the fields!
 * (2) Use the right millis (as usual) for getOffset(); they were passing
 *     in the MILLIS field, instead of the STANDARD MILLIS IN DAY.
 * When you fix these two problems, the test passes, as expected.
 */
@Test
public void Test4126678() {
// Note: this test depends on the PST time zone.
TimeZone initialZone = TimeZone.getDefault();
    Calendar cal = Calendar.getInstance();
    TimeZone tz = TimeZone.getTimeZone("PST");
TimeZone.setDefault(tz);
    cal.setTimeZone(tz);

    java.util.Calendar tempcal = java.util.Calendar.getInstance();
    tempcal.clear();
    tempcal.set(1998, Calendar.APRIL, 5, 10, 0);
    Date dt = tempcal.getTime();
// the dt value is local time in PST.
    if (!tz.inDaylightTime(dt))
        errln("We're not in Daylight Savings Time and we should be.\n");

    cal.setTime(dt);
    int era = cal.get(Calendar.ERA);
    int year = cal.get(Calendar.YEAR);
    int month = cal.get(Calendar.MONTH);
    int day = cal.get(Calendar.DATE);
    int dayOfWeek = cal.get(Calendar.DAY_OF_WEEK);
    int millis = cal.get(Calendar.MILLISECOND) +
        (cal.get(Calendar.SECOND) +
         (cal.get(Calendar.MINUTE) +
          (cal.get(Calendar.HOUR) * 60) * 60) * 1000) -
        cal.get(Calendar.DST_OFFSET);

    long offset = tz.getOffset(era, year, month, day, dayOfWeek, millis);
    long raw_offset = tz.getRawOffset();
    if (offset == raw_offset)
        errln("Offsets should not match when in DST");

// restore the initial time zone so that this test case
// doesn't affect the others.
TimeZone.setDefault(initialZone);
}
 
Example 14
Source File: CalendarView.java    From android_9.0.0_r45 with Apache License 2.0 5 votes vote down vote up
/**
 * Utility method for the date format used by CalendarView's min/max date.
 *
 * @hide Use only as directed. For internal use only.
 */
public static boolean parseDate(String date, Calendar outDate) {
    if (date == null || date.isEmpty()) {
        return false;
    }

    try {
        final Date parsedDate = DATE_FORMATTER.parse(date);
        outDate.setTime(parsedDate);
        return true;
    } catch (ParseException e) {
        Log.w(LOG_TAG, "Date: " + date + " not in format: " + DATE_FORMAT);
        return false;
    }
}
 
Example 15
Source File: CalendarRegressionTest.java    From j2objc with Apache License 2.0 5 votes vote down vote up
@Test
public void Test4083167() {
    TimeZone saveZone = TimeZone.getDefault();
    try {
        TimeZone.setDefault(TimeZone.getTimeZone("UTC"));
        Date firstDate = new Date();
        Calendar cal = new GregorianCalendar();
        cal.setTime(firstDate);
        long firstMillisInDay = cal.get(Calendar.HOUR_OF_DAY) * 3600000L +
            cal.get(Calendar.MINUTE) * 60000L +
            cal.get(Calendar.SECOND) * 1000L +
            cal.get(Calendar.MILLISECOND);
        
        logln("Current time: " + firstDate.toString());

        for (int validity=0; validity<30; validity++) {
            Date lastDate = new Date(firstDate.getTime() +
                                     (long)validity*1000*24*60*60);
            cal.setTime(lastDate);
            long millisInDay = cal.get(Calendar.HOUR_OF_DAY) * 3600000L +
                cal.get(Calendar.MINUTE) * 60000L +
                cal.get(Calendar.SECOND) * 1000L +
                cal.get(Calendar.MILLISECOND);
            if (firstMillisInDay != millisInDay) 
                errln("Day has shifted " + lastDate);
        }
    }
    finally {
        TimeZone.setDefault(saveZone);
    }
}
 
Example 16
Source File: CalendarRegressionTest.java    From j2objc with Apache License 2.0 4 votes vote down vote up
@Test
public void Test4108764() {
    java.util.Calendar tempcal = java.util.Calendar.getInstance();
    tempcal.clear();
    tempcal.set(1997, Calendar.FEBRUARY, 15, 12, 00, 00);
    Date d00 = tempcal.getTime();
    tempcal.set(1997, Calendar.FEBRUARY, 15, 12, 00, 56);
    Date d01 = tempcal.getTime();
    tempcal.set(1997, Calendar.FEBRUARY, 15, 12, 34, 00);
    Date d10 = tempcal.getTime();
    tempcal.set(1997, Calendar.FEBRUARY, 15, 12, 34, 56);
    Date d11 = tempcal.getTime();
    tempcal.set(1997, Calendar.JANUARY, 15, 12, 34, 56);
    Date dM  = tempcal.getTime();
    tempcal.clear();
    tempcal.set(1970, Calendar.JANUARY, 1);
    Date epoch = tempcal.getTime();

    Calendar cal = Calendar.getInstance(); 
    cal.setTime(d11);

    cal.clear( Calendar.MINUTE ); 
    logln(cal.getTime().toString()); 
    if (!cal.getTime().equals(d01)) {
        errln("Fail: " + d11 + " clear(MINUTE) => expect " +
              d01 + ", got " + cal.getTime());
    }

    cal.set( Calendar.SECOND, 0 ); 
    logln(cal.getTime().toString()); 
    if (!cal.getTime().equals(d00))
        errln("Fail: set(SECOND, 0) broken");

    cal.setTime(d11);
    cal.set( Calendar.SECOND, 0 ); 
    logln(cal.getTime().toString()); 
    if (!cal.getTime().equals(d10))
        errln("Fail: set(SECOND, 0) broken #2");

    cal.clear( Calendar.MINUTE ); 
    logln(cal.getTime().toString()); 
    if (!cal.getTime().equals(d00))
        errln("Fail: clear(MINUTE) broken #2");

    cal.clear();
    logln(cal.getTime().toString());
    if (!cal.getTime().equals(epoch))
        errln("Fail: after clear() expect " + epoch + ", got " + cal.getTime());

    cal.setTime(d11);
    cal.clear( Calendar.MONTH ); 
    logln(cal.getTime().toString()); 
    if (!cal.getTime().equals(dM)) {
        errln("Fail: " + d11 + " clear(MONTH) => expect " +
              dM + ", got " + cal.getTime());
    }
}
 
Example 17
Source File: CalendarRegressionTest.java    From j2objc with Apache License 2.0 4 votes vote down vote up
/**
 * Test fieldDifference().
 */
@Test
public void TestJ438() throws Exception {
    int DATA[] = {
        2000, Calendar.JANUARY, 20,   2010, Calendar.JUNE, 15,
        2010, Calendar.JUNE, 15,      2000, Calendar.JANUARY, 20,
        1964, Calendar.SEPTEMBER, 7,  1999, Calendar.JUNE, 4,
        1999, Calendar.JUNE, 4,       1964, Calendar.SEPTEMBER, 7,
    };
    Calendar cal = Calendar.getInstance(Locale.US);
    for (int i=0; i<DATA.length; i+=6) {
        int y1 = DATA[i];
        int m1 = DATA[i+1];
        int d1 = DATA[i+2];
        int y2 = DATA[i+3];
        int m2 = DATA[i+4];
        int d2 = DATA[i+5];

        cal.clear();
        cal.set(y1, m1, d1);
        Date date1 = cal.getTime();
        cal.set(y2, m2, d2);
        Date date2 = cal.getTime();

        cal.setTime(date1);
        int dy = cal.fieldDifference(date2, Calendar.YEAR);
        int dm = cal.fieldDifference(date2, Calendar.MONTH);
        int dd = cal.fieldDifference(date2, Calendar.DATE);

        logln("" + date2 + " - " + date1 + " = " +
              dy + "y " + dm + "m " + dd + "d");

        cal.setTime(date1);
        cal.add(Calendar.YEAR, dy);
        cal.add(Calendar.MONTH, dm);
        cal.add(Calendar.DATE, dd);
        Date date22 = cal.getTime();
        if (!date2.equals(date22)) {
            errln("FAIL: " + date1 + " + " +
                  dy + "y " + dm + "m " + dd + "d = " +
                  date22 + ", exp " + date2);
        } else {
            logln("Ok: " + date1 + " + " +
                  dy + "y " + dm + "m " + dd + "d = " +
                  date22);
        }
    }
}
 
Example 18
Source File: CalendarRegressionTest.java    From j2objc with Apache License 2.0 4 votes vote down vote up
@Test
public void Test4096231() {
    TimeZone GMT = TimeZone.getTimeZone("GMT");
    TimeZone PST = TimeZone.getTimeZone("PST");
    int sec = 0, min = 0, hr = 0, day = 1, month = 10, year = 1997;
                        
    Calendar cal1 = new GregorianCalendar(PST);
    cal1.setTime(new Date(880698639000L));
    int p;
    logln("PST 1 is: " + (p=cal1.get(Calendar.HOUR_OF_DAY)));
    cal1.setTimeZone(GMT);
    // Issue 1: Changing the timezone doesn't change the
    //          represented time.
    int h1,h2;
    logln("GMT 1 is: " + (h1=cal1.get(Calendar.HOUR_OF_DAY)));
    cal1.setTime(new Date(880698639000L));
    logln("GMT 2 is: " + (h2=cal1.get(Calendar.HOUR_OF_DAY)));
    // Note: This test had a bug in it. It wanted h1!=h2, when
    // what was meant was h1!=p. Fixed this concurrent with fix
    // to 4177484.
    if (p == h1 || h1 != h2)
        errln("Fail: Hour same in different zones");

    Calendar cal2 = new GregorianCalendar(GMT);
    Calendar cal3 = new GregorianCalendar(PST);
    cal2.set(Calendar.MILLISECOND, 0);
    cal3.set(Calendar.MILLISECOND, 0);

    cal2.set(cal1.get(Calendar.YEAR),
             cal1.get(Calendar.MONTH),
             cal1.get(Calendar.DAY_OF_MONTH),
             cal1.get(Calendar.HOUR_OF_DAY),
             cal1.get(Calendar.MINUTE),
             cal1.get(Calendar.SECOND));

    long t1,t2,t3,t4;
    logln("RGMT 1 is: " + (t1=cal2.getTime().getTime()));
    cal3.set(year, month, day, hr, min, sec);
    logln("RPST 1 is: " + (t2=cal3.getTime().getTime()));
    cal3.setTimeZone(GMT);
    logln("RGMT 2 is: " + (t3=cal3.getTime().getTime()));
    cal3.set(cal1.get(Calendar.YEAR),
             cal1.get(Calendar.MONTH),
             cal1.get(Calendar.DAY_OF_MONTH),
             cal1.get(Calendar.HOUR_OF_DAY),
             cal1.get(Calendar.MINUTE),
             cal1.get(Calendar.SECOND));
    // Issue 2: Calendar continues to use the timezone in its
    //          constructor for set() conversions, regardless
    //          of calls to setTimeZone()
    logln("RGMT 3 is: " + (t4=cal3.getTime().getTime()));
    if (t1 == t2 ||
        t1 != t4 ||
        t2 != t3)
        errln("Fail: Calendar zone behavior faulty");
}
 
Example 19
Source File: IBMCalendarTest.java    From j2objc with Apache License 2.0 4 votes vote down vote up
/**
 * Run a test of a quasi-Gregorian calendar.  This is a calendar
 * that behaves like a Gregorian but has different year/era mappings.
 * The int[] data array should have the format:
 *
 * { era, year, gregorianYear, month, dayOfMonth, ... }
 */
void quasiGregorianTest(Calendar cal, int[] data) {
    // As of JDK 1.4.1_01, using the Sun JDK GregorianCalendar as
    // a reference throws us off by one hour.  This is most likely
    // due to the JDK 1.4 incorporation of historical time zones.
    //java.util.Calendar grego = java.util.Calendar.getInstance();
    Calendar grego = Calendar.getInstance();
    for (int i=0; i<data.length; ) {
        int era = data[i++];
        int year = data[i++];
        int gregorianYear = data[i++];
        int month = data[i++];
        int dayOfMonth = data[i++];

        grego.clear();
        grego.set(gregorianYear, month, dayOfMonth);
        Date D = grego.getTime();

        cal.clear();
        cal.set(Calendar.ERA, era);
        cal.set(year, month, dayOfMonth);
        Date d = cal.getTime();
        if (d.equals(D)) {
            logln("OK: " + era + ":" + year + "/" + (month+1) + "/" + dayOfMonth +
                  " => " + d);
        } else {
            errln("Fail: " + era + ":" + year + "/" + (month+1) + "/" + dayOfMonth +
                  " => " + d + ", expected " + D);
        }

        cal.clear();
        cal.setTime(D);
        int e = cal.get(Calendar.ERA);
        int y = cal.get(Calendar.YEAR);
        if (y == year && e == era) {
            logln("OK: " + D + " => " + cal.get(Calendar.ERA) + ":" +
                  cal.get(Calendar.YEAR) + "/" +
                  (cal.get(Calendar.MONTH)+1) + "/" + cal.get(Calendar.DATE));
        } else {
            logln("Fail: " + D + " => " + cal.get(Calendar.ERA) + ":" +
                  cal.get(Calendar.YEAR) + "/" +
                  (cal.get(Calendar.MONTH)+1) + "/" + cal.get(Calendar.DATE) +
                  ", expected " + era + ":" + year + "/" + (month+1) + "/" +
                  dayOfMonth);
        }
    }
}
 
Example 20
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());
          }
      }
}