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

The following examples show how to use android.icu.util.Calendar#add() . 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
void marchByDelta(Calendar cal, int delta) {
    Calendar cur = (Calendar)cal.clone();
    int initialDOW = cur.get(Calendar.DAY_OF_WEEK);
    int DOW, newDOW = initialDOW;
    do {
        DOW = newDOW;
        logln("DOW = " + DOW + "  " + cur.getTime());

        cur.add(Calendar.DAY_OF_WEEK, delta);
        newDOW = cur.get(Calendar.DAY_OF_WEEK);
        int expectedDOW = 1 + (DOW + delta - 1) % 7;
        if (newDOW != expectedDOW) {
            errln("Day of week should be " + expectedDOW +
                  " instead of " + newDOW + " on " + cur.getTime());
            return;
        }
    }
    while (newDOW != initialDOW);
}
 
Example 3
Source File: TwilightService.java    From android_9.0.0_r45 with Apache License 2.0 5 votes vote down vote up
/**
 * Calculates the twilight state for a specific location and time.
 *
 * @param location the location to use
 * @param timeMillis the reference time to use
 * @return the calculated {@link TwilightState}, or {@code null} if location is {@code null}
 */
private static TwilightState calculateTwilightState(Location location, long timeMillis) {
    if (location == null) {
        return null;
    }

    final CalendarAstronomer ca = new CalendarAstronomer(
            location.getLongitude(), location.getLatitude());

    final Calendar noon = Calendar.getInstance();
    noon.setTimeInMillis(timeMillis);
    noon.set(Calendar.HOUR_OF_DAY, 12);
    noon.set(Calendar.MINUTE, 0);
    noon.set(Calendar.SECOND, 0);
    noon.set(Calendar.MILLISECOND, 0);
    ca.setTime(noon.getTimeInMillis());

    long sunriseTimeMillis = ca.getSunRiseSet(true /* rise */);
    long sunsetTimeMillis = ca.getSunRiseSet(false /* rise */);

    if (sunsetTimeMillis < timeMillis) {
        noon.add(Calendar.DATE, 1);
        ca.setTime(noon.getTimeInMillis());
        sunriseTimeMillis = ca.getSunRiseSet(true /* rise */);
    } else if (sunriseTimeMillis > timeMillis) {
        noon.add(Calendar.DATE, -1);
        ca.setTime(noon.getTimeInMillis());
        sunsetTimeMillis = ca.getSunRiseSet(false /* rise */);
    }

    return new TwilightState(sunriseTimeMillis, sunsetTimeMillis);
}
 
Example 4
Source File: TimeZoneRegressionTest.java    From j2objc with Apache License 2.0 5 votes vote down vote up
/**
 * TimeZone broken in last hour of year
 */
@Test
public void Test4173604() {
    TimeZone pst = TimeZone.getTimeZone("PST");
    int o22 = pst.getOffset(1, 1998, 11, 31, Calendar.THURSDAY, 22*60*60*1000);
    int o23 = pst.getOffset(1, 1998, 11, 31, Calendar.THURSDAY, 23*60*60*1000);
    int o00 = pst.getOffset(1, 1999, 0, 1, Calendar.FRIDAY, 0);
    if (o22 != o23 || o22 != o00) {
        errln("Offsets should be the same (for PST), but got: " +
              "12/31 22:00 " + o22 +
              ", 12/31 23:00 " + o23 +
              ", 01/01 00:00 " + o00);
    }

    GregorianCalendar cal = new GregorianCalendar();
    cal.setTimeZone(pst);
    cal.clear();
    cal.set(1998, Calendar.JANUARY, 1);
    int lastDST = cal.get(Calendar.DST_OFFSET);
    int transitions = 0;
    int delta = 5;
    while (cal.get(Calendar.YEAR) < 2000) {
        cal.add(Calendar.MINUTE, delta);
        if (cal.get(Calendar.DST_OFFSET) != lastDST) {
            ++transitions;
            Calendar t = (Calendar)cal.clone();
            t.add(Calendar.MINUTE, -delta);
            logln(t.getTime() + "  " + t.get(Calendar.DST_OFFSET));
            logln(cal.getTime() + "  " + (lastDST=cal.get(Calendar.DST_OFFSET)));
        }
    }
    if (transitions != 4) {
        errln("Saw " + transitions + " transitions; should have seen 4");
    }
}
 
Example 5
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 6
Source File: DateTimeView.java    From android_9.0.0_r45 with Apache License 2.0 5 votes vote down vote up
/**
 * @param timeZone the timezone we are in
 * @return the timepoint in millis at UTC at midnight in the current timezone
 */
private long computeNextMidnight(TimeZone timeZone) {
    Calendar c = Calendar.getInstance();
    c.setTimeZone(libcore.icu.DateUtilsBridge.icuTimeZone(timeZone));
    c.add(Calendar.DAY_OF_MONTH, 1);
    c.set(Calendar.HOUR_OF_DAY, 0);
    c.set(Calendar.MINUTE, 0);
    c.set(Calendar.SECOND, 0);
    c.set(Calendar.MILLISECOND, 0);
    return c.getTimeInMillis();
}
 
Example 7
Source File: CalendarRegressionTest.java    From j2objc with Apache License 2.0 5 votes vote down vote up
@Test
public void Test4040996() {
    try {
        String[] ids = TimeZone.getAvailableIDs(-8 * 60 * 60 * 1000);
        SimpleTimeZone pdt = new SimpleTimeZone(-8 * 60 * 60 * 1000, ids[0]);
        pdt.setStartRule(Calendar.APRIL, 1, Calendar.SUNDAY, 2 * 60 * 60 * 1000);
        pdt.setEndRule(Calendar.OCTOBER, -1, Calendar.SUNDAY, 2 * 60 * 60 * 1000);
        Calendar calendar = new GregorianCalendar(pdt);

        calendar.set(Calendar.MONTH,3);
        calendar.set(Calendar.DAY_OF_MONTH,18);
        calendar.set(Calendar.SECOND, 30);

        logln("MONTH: " + calendar.get(Calendar.MONTH));
        logln("DAY_OF_MONTH: " + 
                           calendar.get(Calendar.DAY_OF_MONTH));
        logln("MINUTE: " + calendar.get(Calendar.MINUTE));
        logln("SECOND: " + calendar.get(Calendar.SECOND));

        calendar.add(Calendar.SECOND,6);
        //This will print out todays date for MONTH and DAY_OF_MONTH
        //instead of the date it was set to.
        //This happens when adding MILLISECOND or MINUTE also
        logln("MONTH: " + calendar.get(Calendar.MONTH));
        logln("DAY_OF_MONTH: " + 
                           calendar.get(Calendar.DAY_OF_MONTH));
        logln("MINUTE: " + calendar.get(Calendar.MINUTE));
        logln("SECOND: " + calendar.get(Calendar.SECOND));
        if (calendar.get(Calendar.MONTH) != 3 ||
            calendar.get(Calendar.DAY_OF_MONTH) != 18 ||
            calendar.get(Calendar.SECOND) != 36)
            errln("Fail: Calendar.add misbehaves");
    } catch (Exception e) {
        warnln("Could not load data. "+ e.getMessage());
    }
}
 
Example 8
Source File: CalendarRegressionTest.java    From j2objc with Apache License 2.0 5 votes vote down vote up
@Test
public void TestT5555() throws Exception
{
    Calendar cal = Calendar.getInstance();
    
    // Set date to Wednesday, February 21, 2007
    cal.set(2007, Calendar.FEBRUARY, 21);

    try {
        // Advance month by three years
        cal.add(Calendar.MONTH, 36);
        
        // Move to last Wednesday of month.
        cal.set(Calendar.DAY_OF_WEEK_IN_MONTH, -1);
        
        cal.getTime();
    } catch (Exception e) {
        errln("Got an exception calling getTime().");
    }
    
    int yy, mm, dd, ee;
    
    yy = cal.get(Calendar.YEAR);
    mm = cal.get(Calendar.MONTH);
    dd = cal.get(Calendar.DATE);
    ee = cal.get(Calendar.DAY_OF_WEEK_IN_MONTH);
    
    if (yy != 2010 || mm != Calendar.FEBRUARY || dd != 24 || ee != Calendar.WEDNESDAY) {
        errln("Got date " + yy + "/" + (mm + 1) + "/" + dd + ", expected 2010/2/24");
    }
}
 
Example 9
Source File: IndianTest.java    From j2objc with Apache License 2.0 5 votes vote down vote up
/**
 * Problem reported by Bruno Haible <[email protected]>
 *  -- see ticket 8419 -- http://bugs.icu-project.org/trac/ticket/8419
 * Problem with months out of range 0-11
 */
@Test
public void TestYearEdge() {
    // Display dates in ISO 8601 format.
    DateFormat fmt = new SimpleDateFormat("YYYY-MM-dd", ULocale.US);

    // Instantiate an Indian calendar.
    ULocale locale = ULocale.US.setKeywordValue("calendar", "indian");
    Calendar cal = Calendar.getInstance(locale);

    // Try add() repeatedly.
    cal.setTimeInMillis(1295568000000L);
    if (!fmt.format(cal.getTime()).equals("2011-01-20")){
        errln("Incorrect calendar value for year edge test");
    }
    cal.add(Calendar.MONTH, 1);
    if (!fmt.format(cal.getTime()).equals("2011-02-19")){
        errln("Incorrect calendar value for year edge test");
    }
    cal.add(Calendar.MONTH, 1);
    if (!fmt.format(cal.getTime()).equals("2011-03-21")){
        errln("Incorrect calendar value for year edge test");
    }
    cal.add(Calendar.MONTH, 1);
    if (!fmt.format(cal.getTime()).equals("2011-04-20")){
        errln("Incorrect calendar value for year edge test");
    }
}
 
Example 10
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 11
Source File: CalendarTestFmwk.java    From j2objc with Apache License 2.0 5 votes vote down vote up
/**
 * Process test cases for <code>add</code> and <code>roll</code> methods.
 * Each test case is an array of integers, as follows:
 * <ul>
 *  <li>0: input year
 *  <li>1:       month  (zero-based)
 *  <li>2:       day
 *  <li>3: field to roll or add to
 *  <li>4: amount to roll or add
 *  <li>5: result year
 *  <li>6:        month (zero-based)
 *  <li>7:        day
 * </ul>
 * For example:
 * <pre>
 *   //       input                add by          output
 *   //  year  month     day     field amount    year  month     day
 *   {   5759, HESHVAN,   2,     MONTH,   1,     5759, KISLEV,    2 },
 * </pre>
 *
 * @param roll  <code>true</code> or <code>ROLL</code> to test the <code>roll</code> method;
 *              <code>false</code> or <code>ADD</code> to test the <code>add</code method
 */
protected void doRollAdd(boolean roll, Calendar cal, int[][] tests)
{
    String name = roll ? "rolling" : "adding";
    
    for (int i = 0; i < tests.length; i++) {
        int[] test = tests[i];

        cal.clear();
        if (cal instanceof ChineseCalendar) {
            cal.set(Calendar.EXTENDED_YEAR, test[0]);
            cal.set(Calendar.MONTH, test[1]);
            cal.set(Calendar.DAY_OF_MONTH, test[2]);
        } else {
            cal.set(test[0], test[1], test[2]);
        }
        double day0 = getJulianDay(cal);
        if (roll) {
            cal.roll(test[3], test[4]);
        } else {
            cal.add(test[3], test[4]);
        }
        int y = cal.get(cal instanceof ChineseCalendar ?
                        Calendar.EXTENDED_YEAR : YEAR);
        if (y != test[5] || cal.get(MONTH) != test[6]
                || cal.get(DATE) != test[7])
        {
            errln("Fail: " + name + " "+ ymdToString(test[0], test[1], test[2])
                + " (" + day0 + ")"
                + " " + FIELD_NAME[test[3]] + " by " + test[4]
                + ": expected " + ymdToString(test[5], test[6], test[7])
                + ", got " + ymdToString(cal));
        } else if (isVerbose()) {
            logln("OK: " + name + " "+ ymdToString(test[0], test[1], test[2])
                + " (" + day0 + ")"
                + " " + FIELD_NAME[test[3]] + " by " + test[4]
                + ": got " + ymdToString(cal));
        }
    }
}
 
Example 12
Source File: DangiTest.java    From j2objc with Apache License 2.0 5 votes vote down vote up
void doRollAddDangi(boolean roll, Calendar cal, int[][] tests) {
    String name = roll ? "rolling" : "adding";

    for (int i = 0; i < tests.length; i++) {
        int[] test = tests[i];

        cal.clear();
        cal.set(Calendar.EXTENDED_YEAR, test[0]);
        cal.set(Calendar.MONTH, test[1] - 1);
        cal.set(Calendar.IS_LEAP_MONTH, test[2]);
        cal.set(Calendar.DAY_OF_MONTH, test[3]);
        if (roll) {
            cal.roll(test[4], test[5]);
        } else {
            cal.add(test[4], test[5]);
        }
        if (cal.get(Calendar.EXTENDED_YEAR) != test[6] || cal.get(MONTH) != (test[7] - 1)
                || cal.get(Calendar.IS_LEAP_MONTH) != test[8] || cal.get(DATE) != test[9]) {
            errln("Fail: " + name + " " + ymdToString(test[0], test[1] - 1, test[2], test[3]) + " "
                    + fieldName(test[4]) + " by " + test[5] + ": expected "
                    + ymdToString(test[6], test[7] - 1, test[8], test[9]) + ", got " + ymdToString(cal));
        } else if (isVerbose()) {
            logln("OK: " + name + " " + ymdToString(test[0], test[1] - 1, test[2], test[3]) + " "
                    + fieldName(test[4]) + " by " + test[5] + ": got " + ymdToString(cal));
        }
    }
}
 
Example 13
Source File: DangiTest.java    From j2objc with Apache License 2.0 5 votes vote down vote up
@Test
public void TestInitWithCurrentTime() {
    // If the chinese calendar current millis isn't called, the default year is wrong.
    // this test is assuming the 'year' is the current cycle
    // so when we cross a cycle boundary, the target will need to change
    // that shouldn't be for awhile yet... 

    Calendar cc = Calendar.getInstance(new ULocale("ko_KR@calendar=dangi"));
    cc.set(Calendar.EXTENDED_YEAR, 4338);
    cc.set(Calendar.MONTH, 0);
     // need to set leap month flag off, otherwise, the test case always fails when
     // current time is in a leap month
    cc.set(Calendar.IS_LEAP_MONTH, 0);
    cc.set(Calendar.DATE, 19);
    cc.set(Calendar.HOUR_OF_DAY, 0);
    cc.set(Calendar.MINUTE, 0);
    cc.set(Calendar.SECOND, 0);
    cc.set(Calendar.MILLISECOND, 0);

    cc.add(Calendar.DATE, 1);
 
    Calendar cal = new GregorianCalendar(2005, Calendar.FEBRUARY, 28);
    Date target = cal.getTime();
    Date result = cc.getTime();

    assertEquals("chinese and gregorian date should match", target, result);
}
 
Example 14
Source File: CopticTest.java    From j2objc with Apache License 2.0 5 votes vote down vote up
@Test
public void TestYear() {
    // Gregorian Calendar
    Calendar gCal= new GregorianCalendar();
    Date gToday=gCal.getTime();
    gCal.add(GregorianCalendar.MONTH,2);
    Date gFuture=gCal.getTime();
    DateFormat gDF = DateFormat.getDateInstance(gCal,DateFormat.FULL);
    logln("gregorian calendar: " + gDF.format(gToday) +
          " + 2 months = " + gDF.format(gFuture));

    // Coptic Calendar
    CopticCalendar cCal= new CopticCalendar();
    Date cToday=cCal.getTime();
    cCal.add(CopticCalendar.MONTH,2);
    Date cFuture=cCal.getTime();
    DateFormat cDF = DateFormat.getDateInstance(cCal,DateFormat.FULL);
    logln("coptic calendar: " + cDF.format(cToday) +
          " + 2 months = " + cDF.format(cFuture));

    // EthiopicCalendar
    EthiopicCalendar eCal= new EthiopicCalendar();
    Date eToday=eCal.getTime();
    eCal.add(EthiopicCalendar.MONTH,2); // add 2 months
    eCal.setAmeteAlemEra(false);
    Date eFuture=eCal.getTime();
    DateFormat eDF = DateFormat.getDateInstance(eCal,DateFormat.FULL);
    logln("ethiopic calendar: " + eDF.format(eToday) +
          " + 2 months = " + eDF.format(eFuture));
}
 
Example 15
Source File: IBMCalendarTest.java    From j2objc with Apache License 2.0 5 votes vote down vote up
/**
 * Make sure that when adding a day, we actually wind up in a
 * different day.  The DST adjustments we use to keep the hour
 * constant across DST changes can backfire and change the day.
 */
@Test
public void TestTimeZoneTransitionAdd() {
    Locale locale = Locale.US; // could also be CHINA
    SimpleDateFormat dateFormat =
        new SimpleDateFormat("MM/dd/yyyy HH:mm z", locale);

    String tz[] = TimeZone.getAvailableIDs();

    for (int z=0; z<tz.length; ++z) {
        TimeZone t = TimeZone.getTimeZone(tz[z]);
        dateFormat.setTimeZone(t);

        Calendar cal = Calendar.getInstance(t, locale);
        cal.clear();
        // Scan the year 2003, overlapping the edges of the year
        cal.set(Calendar.YEAR, 2002);
        cal.set(Calendar.MONTH, Calendar.DECEMBER);
        cal.set(Calendar.DAY_OF_MONTH, 25);

        for (int i=0; i<365+10; ++i) {
            Date yesterday = cal.getTime();
            int yesterday_day = cal.get(Calendar.DAY_OF_MONTH);
            cal.add(Calendar.DAY_OF_MONTH, 1);
            if (yesterday_day == cal.get(Calendar.DAY_OF_MONTH)) {
                errln(tz[z] + " " +
                      dateFormat.format(yesterday) + " +1d= " +
                      dateFormat.format(cal.getTime()));
            }
        }
    }
}
 
Example 16
Source File: CalendarRegressionTest.java    From j2objc with Apache License 2.0 4 votes vote down vote up
@Test
public void Test4114578() {
    int ONE_HOUR = 60*60*1000;
    Calendar cal = Calendar.getInstance();
    cal.setTimeZone(TimeZone.getTimeZone("PST"));
    
    java.util.Calendar tempcal = java.util.Calendar.getInstance();
    tempcal.clear();
    tempcal.set(1998, Calendar.APRIL, 5, 1, 0);
    long onset = tempcal.getTime().getTime() + ONE_HOUR;
    tempcal.set(1998, Calendar.OCTOBER, 25, 0, 0);
    long cease = tempcal.getTime().getTime() + 2*ONE_HOUR;

    boolean fail = false;
    
    final int ADD = 1;
    final int ROLL = 2;

    long[] DATA = {
        // Start Action Amt Expected_change
        onset - ONE_HOUR,   ADD,      1,     ONE_HOUR,
        onset,              ADD,     -1,    -ONE_HOUR,
        onset - ONE_HOUR,   ROLL,     1,     ONE_HOUR,
        onset,              ROLL,    -1,    -ONE_HOUR,
        cease - ONE_HOUR,   ADD,      1,     ONE_HOUR,
        cease,              ADD,     -1,    -ONE_HOUR,
        cease - ONE_HOUR,   ROLL,     1,     ONE_HOUR,
        cease,              ROLL,    -1,    -ONE_HOUR,
    };

    for (int i=0; i<DATA.length; i+=4) {
        Date date = new Date(DATA[i]);
        int amt = (int) DATA[i+2];
        long expectedChange = DATA[i+3];
        
        log(date.toString());
        cal.setTime(date);

        switch ((int) DATA[i+1]) {
        case ADD:
            log(" add (HOUR," + (amt<0?"":"+")+amt + ")= ");
            cal.add(Calendar.HOUR, amt);
            break;
        case ROLL:
            log(" roll(HOUR," + (amt<0?"":"+")+amt + ")= ");
            cal.roll(Calendar.HOUR, amt);
            break;
        }

        log(cal.getTime().toString());

        long change = cal.getTime().getTime() - date.getTime();
        if (change != expectedChange) {
            fail = true;
            logln(" FAIL");
        }
        else logln(" OK");
    }

    if (fail) errln("Fail: roll/add misbehaves around DST onset/cease");
}
 
Example 17
Source File: IBMCalendarTest.java    From j2objc with Apache License 2.0 4 votes vote down vote up
/**
 * setFirstDayOfWeek and setMinimalDaysInFirstWeek may change the
 * field <=> time mapping, since they affect the interpretation of
 * the WEEK_OF_MONTH or WEEK_OF_YEAR fields.
 */
@Test
public void TestWeekShift() {
    Calendar cal = new GregorianCalendar(
                         TimeZone.getTimeZone("America/Los_Angeles"),
                         new Locale("en", "US"));
    cal.setTime(new Date(997257600000L)); // Wed Aug 08 01:00:00 PDT 2001
    // In pass one, change the first day of week so that the weeks
    // shift in August 2001.  In pass two, change the minimal days
    // in the first week so that the weeks shift in August 2001.
    //     August 2001
    // Su Mo Tu We Th Fr Sa
    //           1  2  3  4
    //  5  6  7  8  9 10 11
    // 12 13 14 15 16 17 18
    // 19 20 21 22 23 24 25
    // 26 27 28 29 30 31
    for (int pass=0; pass<2; ++pass) {
        if (pass==0) {
            cal.setFirstDayOfWeek(Calendar.WEDNESDAY);
            cal.setMinimalDaysInFirstWeek(4);
        } else {
            cal.setFirstDayOfWeek(Calendar.SUNDAY);
            cal.setMinimalDaysInFirstWeek(4);
        }
        cal.add(Calendar.DATE, 1); // Force recalc
        cal.add(Calendar.DATE, -1);

        Date time1 = cal.getTime(); // Get time -- should not change

        // Now change a week parameter and then force a recalc.
        // The bug is that the recalc should not be necessary --
        // calendar should do so automatically.
        if (pass==0) {
            cal.setFirstDayOfWeek(Calendar.THURSDAY);
        } else {
            cal.setMinimalDaysInFirstWeek(5);
        }

        int woy1 = cal.get(Calendar.WEEK_OF_YEAR);
        int wom1 = cal.get(Calendar.WEEK_OF_MONTH);

        cal.add(Calendar.DATE, 1); // Force recalc
        cal.add(Calendar.DATE, -1);

        int woy2 = cal.get(Calendar.WEEK_OF_YEAR);
        int wom2 = cal.get(Calendar.WEEK_OF_MONTH);

        Date time2 = cal.getTime();

        if (!time1.equals(time2)) {
            errln("FAIL: shifting week should not alter time");
        } else {
            logln(time1.toString());
        }
        if (woy1 == woy2 && wom1 == wom2) {
            logln("Ok: WEEK_OF_YEAR: " + woy1 +
                  ", WEEK_OF_MONTH: " + wom1);
        } else {
            errln("FAIL: WEEK_OF_YEAR: " + woy1 + " => " + woy2 +
                  ", WEEK_OF_MONTH: " + wom1 + " => " + wom2 +
                  " after week shift");
        }
    }
}
 
Example 18
Source File: HolidayTest.java    From j2objc with Apache License 2.0 4 votes vote down vote up
@Test
public void TestIsOn() {
    // jb 1901
    SimpleHoliday sh = new SimpleHoliday(Calendar.AUGUST, 15, "Doug's Day", 1958, 2058);
    
    Calendar gcal = new GregorianCalendar();
    gcal.clear();
    gcal.set(Calendar.YEAR, 2000);
    gcal.set(Calendar.MONTH, Calendar.AUGUST);
    gcal.set(Calendar.DAY_OF_MONTH, 15);
    
    Date d0 = gcal.getTime();
    gcal.add(Calendar.SECOND, 1);
    Date d1 = gcal.getTime();
    gcal.add(Calendar.SECOND, -2);
    Date d2 = gcal.getTime();
    gcal.add(Calendar.DAY_OF_MONTH, 1);
    Date d3 = gcal.getTime();
    gcal.add(Calendar.SECOND, 1);
    Date d4 = gcal.getTime();
    gcal.add(Calendar.SECOND, -2);
    gcal.set(Calendar.YEAR, 1957);
    Date d5 = gcal.getTime();
    gcal.set(Calendar.YEAR, 1958);
    Date d6 = gcal.getTime();
    gcal.set(Calendar.YEAR, 2058);
    Date d7 = gcal.getTime();
    gcal.set(Calendar.YEAR, 2059);
    Date d8 = gcal.getTime();

    Date[] dates = { d0, d1, d2, d3, d4, d5, d6, d7, d8 };
    boolean[] isOns = { true, true, false, true, false, false, true, true, false };
    for (int i = 0; i < dates.length; ++i) {
        Date d = dates[i];
        logln("\ndate: " + d);
        boolean isOn = sh.isOn(d);
        logln("isOnDate: " + isOn);
        if (isOn != isOns[i]) {
            errln("date: " + d + " should be on Doug's Day!");
        }
        Date h = sh.firstAfter(d);
        logln("firstAfter: " + h);
    }
}
 
Example 19
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 20
Source File: CalendarViewLegacyDelegate.java    From android_9.0.0_r45 with Apache License 2.0 4 votes vote down vote up
/**
 * Updates the title and selected month if the <code>view</code> has moved to a new
 * month.
 */
private void onScroll(AbsListView view, int firstVisibleItem, int visibleItemCount,
                      int totalItemCount) {
    WeekView child = (WeekView) view.getChildAt(0);
    if (child == null) {
        return;
    }

    // Figure out where we are
    long currScroll =
            view.getFirstVisiblePosition() * child.getHeight() - child.getBottom();

    // If we have moved since our last call update the direction
    if (currScroll < mPreviousScrollPosition) {
        mIsScrollingUp = true;
    } else if (currScroll > mPreviousScrollPosition) {
        mIsScrollingUp = false;
    } else {
        return;
    }

    // Use some hysteresis for checking which month to highlight. This
    // causes the month to transition when two full weeks of a month are
    // visible when scrolling up, and when the first day in a month reaches
    // the top of the screen when scrolling down.
    int offset = child.getBottom() < mWeekMinVisibleHeight ? 1 : 0;
    if (mIsScrollingUp) {
        child = (WeekView) view.getChildAt(SCROLL_HYST_WEEKS + offset);
    } else if (offset != 0) {
        child = (WeekView) view.getChildAt(offset);
    }

    if (child != null) {
        // Find out which month we're moving into
        int month;
        if (mIsScrollingUp) {
            month = child.getMonthOfFirstWeekDay();
        } else {
            month = child.getMonthOfLastWeekDay();
        }

        // And how it relates to our current highlighted month
        int monthDiff;
        if (mCurrentMonthDisplayed == 11 && month == 0) {
            monthDiff = 1;
        } else if (mCurrentMonthDisplayed == 0 && month == 11) {
            monthDiff = -1;
        } else {
            monthDiff = month - mCurrentMonthDisplayed;
        }

        // Only switch months if we're scrolling away from the currently
        // selected month
        if ((!mIsScrollingUp && monthDiff > 0) || (mIsScrollingUp && monthDiff < 0)) {
            Calendar firstDay = child.getFirstDay();
            if (mIsScrollingUp) {
                firstDay.add(Calendar.DAY_OF_MONTH, -DAYS_PER_WEEK);
            } else {
                firstDay.add(Calendar.DAY_OF_MONTH, DAYS_PER_WEEK);
            }
            setMonthDisplayed(firstDay);
        }
    }
    mPreviousScrollPosition = currScroll;
    mPreviousScrollState = mCurrentScrollState;
}