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

The following examples show how to use android.icu.util.Calendar#setTimeZone() . 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: 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 2
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 3
Source File: CalendarRegressionTest.java    From j2objc with Apache License 2.0 5 votes vote down vote up
/**
 * Calendar does not update field values when setTimeZone is called.
 */
@Test
public void Test4177484() {
    TimeZone PST = TimeZone.getTimeZone("PST");
    TimeZone EST = TimeZone.getTimeZone("EST");

    Calendar cal = Calendar.getInstance(PST, Locale.US);
    cal.clear();
    cal.set(1999, 3, 21, 15, 5, 0); // Arbitrary
    int h1 = cal.get(Calendar.HOUR_OF_DAY);
    cal.setTimeZone(EST);
    int h2 = cal.get(Calendar.HOUR_OF_DAY);
    if (h1 == h2) {
        errln("FAIL: Fields not updated after setTimeZone");
    }

    // getTime() must NOT change when time zone is changed.
    // getTime() returns zone-independent time in ms.
    cal.clear();
    cal.setTimeZone(PST);
    cal.set(Calendar.HOUR_OF_DAY, 10);
    Date pst10 = cal.getTime();
    cal.setTimeZone(EST);
    Date est10 = cal.getTime();
    if (!pst10.equals(est10)) {
        errln("FAIL: setTimeZone changed time");
    }
}
 
Example 4
Source File: TimeZoneRegressionTest.java    From j2objc with Apache License 2.0 5 votes vote down vote up
@Test
public void Test4073215() {
    SimpleTimeZone z = new SimpleTimeZone(0, "GMT");
    if (z.useDaylightTime())
        errln("Fail: Fix test to start with non-DST zone");
    z.setStartRule(Calendar.FEBRUARY, 1, Calendar.SUNDAY, 0);
    z.setEndRule(Calendar.MARCH, -1, Calendar.SUNDAY, 0);
    if (!z.useDaylightTime())
        errln("Fail: DST not active");
    Calendar tempcal = Calendar.getInstance();
    tempcal.clear();
    tempcal.setTimeZone(z);
    tempcal.set(1997, Calendar.JANUARY, 31);
    Date d1 = tempcal.getTime();
    if (z.inDaylightTime(d1)) {
        errln("Fail: DST not working as expected");
    } 

    tempcal.set(1997, Calendar.MARCH, 1);
    Date d2 = tempcal.getTime();
    if (!z.inDaylightTime(d2)) {
        errln("Fail: DST not working as expected");
    }
    tempcal.clear();
    tempcal.set(1997, Calendar.MARCH, 31);
    Date d3 = tempcal.getTime();
    if (z.inDaylightTime(d3)) {
        errln("Fail: DST not working as expected");
    } 
}
 
Example 5
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 6
Source File: CalendarTestFmwk.java    From j2objc with Apache License 2.0 4 votes vote down vote up
/**
 * Iterates through a list of calendar <code>TestCase</code> objects and
 * makes sure that the time-to-fields and fields-to-time calculations work
 * correnctly for the values in each test case.
 */
protected void doTestCases(TestCase[] cases, Calendar cal)
{
    cal.setTimeZone(UTC);
    
    // Get a format to use for printing dates in the calendar system we're testing
    DateFormat format = DateFormat.getDateTimeInstance(cal, DateFormat.SHORT, -1, Locale.getDefault());

    final String pattern = (cal instanceof ChineseCalendar) ?
        "E MMl/dd/y G HH:mm:ss.S z" :
        "E, MM/dd/yyyy G HH:mm:ss.S z";

    ((SimpleDateFormat)format).applyPattern(pattern);

    // This format is used for printing Gregorian dates.
    DateFormat gregFormat = new SimpleDateFormat(pattern);
    gregFormat.setTimeZone(UTC);

    GregorianCalendar pureGreg = new GregorianCalendar(UTC);
    pureGreg.setGregorianChange(new Date(Long.MIN_VALUE));
    DateFormat pureGregFmt = new SimpleDateFormat("E M/d/yyyy G");
    pureGregFmt.setCalendar(pureGreg);
    
    // Now iterate through the test cases and see what happens
    for (int i = 0; i < cases.length; i++)
    {
        logln("\ntest case: " + i);
        TestCase test = cases[i];
        
        //
        // First we want to make sure that the millis -> fields calculation works
        // test.applyTime will call setTime() on the calendar object, and
        // test.fieldsEqual will retrieve all of the field values and make sure
        // that they're the same as the ones in the testcase
        //
        test.applyTime(cal);
        if (!test.fieldsEqual(cal, this)) {
            errln("Fail: (millis=>fields) " +
                  gregFormat.format(test.getTime()) + " => " +
                  format.format(cal.getTime()) +
                  ", expected " + test);
        }

        //
        // If that was OK, check the fields -> millis calculation
        // test.applyFields will set all of the calendar's fields to 
        // match those in the test case.
        //
        cal.clear();
        test.applyFields(cal);
        if (!test.equals(cal)) {
            errln("Fail: (fields=>millis) " + test + " => " +
                  pureGregFmt.format(cal.getTime()) +
                  ", expected " + pureGregFmt.format(test.getTime()));
        }
    }
}
 
Example 7
Source File: IBMCalendarTest.java    From j2objc with Apache License 2.0 4 votes vote down vote up
@Test
public void TestRepeatedWallTime() {
    final Object[][] TESTDATA = {
        // Time zone            Input wall time                     WALLTIME_LAST in GMT                WALLTIME_FIRST in GMT
        {"America/New_York",    new CalFields(2011,11,6,0,59,59),   new CalFields(2011,11,6,4,59,59),   new CalFields(2011,11,6,4,59,59)},
        {"America/New_York",    new CalFields(2011,11,6,1,0,0),     new CalFields(2011,11,6,6,0,0),     new CalFields(2011,11,6,5,0,0)},
        {"America/New_York",    new CalFields(2011,11,6,1,0,1),     new CalFields(2011,11,6,6,0,1),     new CalFields(2011,11,6,5,0,1)},
        {"America/New_York",    new CalFields(2011,11,6,1,30,0),    new CalFields(2011,11,6,6,30,0),    new CalFields(2011,11,6,5,30,0)},
        {"America/New_York",    new CalFields(2011,11,6,1,59,59),   new CalFields(2011,11,6,6,59,59),   new CalFields(2011,11,6,5,59,59)},
        {"America/New_York",    new CalFields(2011,11,6,2,0,0),     new CalFields(2011,11,6,7,0,0),     new CalFields(2011,11,6,7,0,0)},
        {"America/New_York",    new CalFields(2011,11,6,2,0,1),     new CalFields(2011,11,6,7,0,1),     new CalFields(2011,11,6,7,0,1)},

        {"Australia/Lord_Howe", new CalFields(2011,4,3,1,29,59),    new CalFields(2011,4,2,14,29,59),   new CalFields(2011,4,2,14,29,59)},
        {"Australia/Lord_Howe", new CalFields(2011,4,3,1,30,0),     new CalFields(2011,4,2,15,0,0),     new CalFields(2011,4,2,14,30,0)},
        {"Australia/Lord_Howe", new CalFields(2011,4,3,1,45,0),     new CalFields(2011,4,2,15,15,0),    new CalFields(2011,4,2,14,45,0)},
        {"Australia/Lord_Howe", new CalFields(2011,4,3,1,59,59),    new CalFields(2011,4,2,15,29,59),   new CalFields(2011,4,2,14,59,59)},
        {"Australia/Lord_Howe", new CalFields(2011,4,3,2,0,0),      new CalFields(2011,4,2,15,30,0),    new CalFields(2011,4,2,15,30,0)},
        {"Australia/Lord_Howe", new CalFields(2011,4,3,2,0,1),      new CalFields(2011,4,2,15,30,1),    new CalFields(2011,4,2,15,30,1)},
    };

    Calendar calGMT = Calendar.getInstance(TimeZone.GMT_ZONE);

    Calendar calDefault = Calendar.getInstance();
    Calendar calLast = Calendar.getInstance();
    Calendar calFirst = Calendar.getInstance();

    calFirst.setRepeatedWallTimeOption(Calendar.WALLTIME_FIRST);
    calLast.setRepeatedWallTimeOption(Calendar.WALLTIME_LAST);

    for (Object[] test : TESTDATA) {
        String tzid = (String)test[0];
        TimeZone tz = TimeZone.getTimeZone(tzid);
        CalFields in = (CalFields)test[1];
        CalFields expLastGMT = (CalFields)test[2];
        CalFields expFirstGMT = (CalFields)test[3];

        // WALLTIME_LAST
        calLast.setTimeZone(tz);
        in.setTo(calLast);
        calGMT.setTimeInMillis(calLast.getTimeInMillis());
        CalFields outLastGMT = CalFields.createFrom(calGMT);
        if (!outLastGMT.equals(expLastGMT)) {
            errln("Fail: WALLTIME_LAST " + in + "[" + tzid + "] is parsed as " + outLastGMT + "[GMT]. Expected: " + expLastGMT + "[GMT]");
        }

        // default
        calDefault.setTimeZone(tz);
        in.setTo(calDefault);
        calGMT.setTimeInMillis(calDefault.getTimeInMillis());
        CalFields outDefGMT = CalFields.createFrom(calGMT);
        if (!outDefGMT.equals(expLastGMT)) {
            errln("Fail: (default) " + in + "[" + tzid + "] is parsed as " + outDefGMT + "[GMT]. Expected: " + expLastGMT + "[GMT]");
        }

        // WALLTIME_FIRST
        calFirst.setTimeZone(tz);
        in.setTo(calFirst);
        calGMT.setTimeInMillis(calFirst.getTimeInMillis());
        CalFields outFirstGMT = CalFields.createFrom(calGMT);
        if (!outFirstGMT.equals(expFirstGMT)) {
            errln("Fail: WALLTIME_FIRST " + in + "[" + tzid + "] is parsed as " + outFirstGMT + "[GMT]. Expected: " + expFirstGMT + "[GMT]");
        }
    }
}
 
Example 8
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 9
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 10
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);
            }
        }
    }
}