Example #1
0
int main(int argc, char **argv) {

    Calendar *cal;
    DateFormat *fmt;
    DateFormat *defFmt;
    UErrorCode status = U_ZERO_ERROR;
    Locale greece("el", "GR");
    UnicodeString str, str2;

    // Create a calendar in the Greek locale
    cal = Calendar::createInstance(greece, status);
    check(status, "Calendar::createInstance");

    // Create a formatter
    fmt = DateFormat::createDateInstance(DateFormat::kFull, greece);
    fmt->setCalendar(*cal);

    // Create a default formatter
    defFmt = DateFormat::createDateInstance(DateFormat::kFull);
    defFmt->setCalendar(*cal);

    // Loop over various months
    for (int32_t month = Calendar::JANUARY;
            month <= Calendar::DECEMBER;
            ++month) {

        // Set the calendar to a date
        cal->clear();
        cal->set(1999, month, 4);

        // Format the date in default locale
        str.remove();
        defFmt->format(cal->getTime(status), str, status);
        check(status, "DateFormat::format");
        printf("Date: ");
        uprintf(escape(str));
        printf("\n");

        // Format the date for Greece
        str.remove();
        fmt->format(cal->getTime(status), str, status);
        check(status, "DateFormat::format");
        printf("Greek formatted date: ");
        uprintf(escape(str));
        printf("\n\n");
    }

    // Clean up
    delete fmt;
    delete cal;

    printf("Exiting successfully\n");
    return 0;
}
Example #2
0
UDate
DateFormat::parse(const UnicodeString& text,
                  ParsePosition& pos) const
{
    UDate d = 0; // Error return UDate is 0 (the epoch)
    if (fCalendar != NULL) {
        Calendar* calClone = fCalendar->clone();
        if (calClone != NULL) {
            int32_t start = pos.getIndex();
            calClone->clear();
            parse(text, *calClone, pos);
            if (pos.getIndex() != start) {
                UErrorCode ec = U_ZERO_ERROR;
                d = calClone->getTime(ec);
                if (U_FAILURE(ec)) {
                    // We arrive here if fCalendar => calClone is non-lenient and
                    // there is an out-of-range field.  We don't know which field
                    // was illegal so we set the error index to the start.
                    pos.setIndex(start);
                    pos.setErrorIndex(start);
                    d = 0;
                }
            }
            delete calClone;
        }
    }
    return d;
}
Example #3
0
void
IslamicCalendar::initializeSystemDefaultCentury()
{
  // initialize systemDefaultCentury and systemDefaultCenturyYear based
  // on the current time.  They'll be set to 80 years before
  // the current time.
  // No point in locking as it should be idempotent.
  if (fgSystemDefaultCenturyStart == fgSystemDefaultCentury)
  {
    UErrorCode status = U_ZERO_ERROR;
    Calendar *calendar = new IslamicCalendar(Locale("ar@calendar=islamic-civil"),status);
    if (calendar != NULL && U_SUCCESS(status))
    {
      calendar->setTime(Calendar::getNow(), status);
      calendar->add(UCAL_YEAR, -80, status);
      UDate    newStart =  calendar->getTime(status);
      int32_t  newYear  =  calendar->get(UCAL_YEAR, status);
      {
        Mutex m;
        fgSystemDefaultCenturyStart = newStart;
        fgSystemDefaultCenturyStartYear = newYear;
      }
      delete calendar;
    }
    // We have no recourse upon failure unless we want to propagate the failure
    // out.
  }
}
// Verify that Gregorian works like Gregorian
void IntlCalendarTest::TestGregorian() { 
    UDate timeA = Calendar::getNow();
    int32_t data[] = { 
        GregorianCalendar::AD, 1868, 1868, UCAL_SEPTEMBER, 8,
        GregorianCalendar::AD, 1868, 1868, UCAL_SEPTEMBER, 9,
        GregorianCalendar::AD, 1869, 1869, UCAL_JUNE, 4,
        GregorianCalendar::AD, 1912, 1912, UCAL_JULY, 29,
        GregorianCalendar::AD, 1912, 1912, UCAL_JULY, 30,
        GregorianCalendar::AD, 1912, 1912, UCAL_AUGUST, 1,
        -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1
    };
    
    Calendar *cal;
    UErrorCode status = U_ZERO_ERROR;
    cal = Calendar::createInstance(/*"de_DE", */ status);
    CHECK(status, UnicodeString("Creating de_CH calendar"));
    // Sanity check the calendar 
    UDate timeB = Calendar::getNow();
    UDate timeCal = cal->getTime(status);

    if(!(timeA <= timeCal) || !(timeCal <= timeB)) {
      errln((UnicodeString)"Error: Calendar time " + timeCal +
            " is not within sampled times [" + timeA + " to " + timeB + "]!");
    }
    // end sanity check

    // Note, the following is a good way to test the sanity of the constructed calendars,
    // using Collation as a delay-loop: 
    //
    // $ intltest  format/IntlCalendarTest  collate/G7CollationTest format/IntlCalendarTest

    quasiGregorianTest(*cal,Locale("fr_FR"),data);
    delete cal;
}
Example #5
0
void DateFormatRegressionTest::Test5554(void)
{
  UErrorCode status = U_ZERO_ERROR;
  UnicodeString pattern("Z","");
  UnicodeString newfoundland("Canada/Newfoundland", "");
  TimeZone *zone = TimeZone::createTimeZone(newfoundland);
  Calendar *cal = new GregorianCalendar(zone, status);
  SimpleDateFormat *sdf = new SimpleDateFormat(pattern,status);
  if (U_FAILURE(status)) {
    dataerrln("Error constructing SimpleDateFormat");
    delete cal;
    delete sdf;
    return;
  }
  cal->set(2007, 1, 14);
  UDate date = cal->getTime(status);
  if (U_FAILURE(status)) {
    errln("Error getting time to format");
    return;
  };
  sdf->adoptCalendar(cal);
  UnicodeString result;
  UnicodeString correct("-0330", "");
  sdf->format(date, result);
  if (result != correct) {
    errln("\nError: Newfoundland Z of Jan 14, 2007 gave '" + result + "', expected '" + correct + "'");
  }
  delete sdf;
}
Example #6
0
UnicodeString& GLUE_SYM (DateFormat ) :: format(  Calendar& cal, UnicodeString& appendTo, FieldPosition& pos) const
{
#if DATE_FE_DEBUG
  fprintf(stderr, "VCF " ICUGLUE_VER_STR " - formatting. \n");
#endif
  int32_t len = appendTo.length();

  UChar junk[200];
  UErrorCode status = U_ZERO_ERROR;

  UFieldPosition pos2;

  int32_t nlen = OICU_udat_format(_this,
                                  cal.getTime(status),
                                  junk,
                                  200,
                                  &pos2,
                                  &status);

  // todo: use pos2
  pos.setBeginIndex(len);
  pos.setEndIndex(len += nlen);
  appendTo.append(junk, nlen);

  return appendTo;
}
Example #7
0
static void getBestPatternExample() {
	    
		u_printf("========================================================================\n");
		u_printf(" getBestPatternExample()\n");
        u_printf("\n");
        u_printf(" Use DateTimePatternGenerator to create customized date/time pattern:\n");
        u_printf(" yQQQQ,yMMMM, MMMMd, hhmm, jjmm per locale\n");
        u_printf("========================================================================\n");
		//! [getBestPatternExample]
	UnicodeString skeletons [] = {
		UnicodeString("yQQQQ"), // year + full name of quarter, i.e., 4th quarter 1999
        UnicodeString("yMMMM"), // year + full name of month, i.e., October 1999
        UnicodeString("MMMMd"), // full name of month + day of the month, i.e., October 25
        UnicodeString("hhmm"),  // 12-hour-cycle format, i.e., 1:32 PM
        UnicodeString("jjmm"), // preferred hour format for the given locale, i.e., 24-hour-cycle format for fr_FR
		0,
	};

	Locale locales[] = {
		Locale ("en_US"),
		Locale ("fr_FR"),
		Locale ("zh_CN"),
	};
	
	const char* filename = "sample.txt";
	/* open a UTF-8 file for writing */
	UFILE* f = u_fopen(filename, "w", NULL,"UTF-8");
	UnicodeString dateReturned;
	UErrorCode status =U_ZERO_ERROR;
	Calendar *cal = Calendar::createInstance(status);
	cal->set (1999,9,13,23,58,59);
	UDate date = cal->getTime(status);
	u_fprintf(f, "%-20S%-20S%-20S%-20S\n", UnicodeString("Skeleton").getTerminatedBuffer(),UnicodeString("en_US").getTerminatedBuffer(),UnicodeString("fr_FR").getTerminatedBuffer(),UnicodeString("zh_CN").getTerminatedBuffer());
	for (int i=0;skeletons[i]!=NULL;i++) {
		u_fprintf(f, "%-20S",skeletons[i].getTerminatedBuffer());
		for (int j=0;j<sizeof(locales)/sizeof(locales[0]);j++) {
			// create a DateTimePatternGenerator instance for given locale
			DateTimePatternGenerator *dtfg= DateTimePatternGenerator::createInstance(locales[j],status);
			// use getBestPattern method to get the best pattern for the given skeleton
			UnicodeString pattern = dtfg->getBestPattern(skeletons[i],status);
			// Constructs a SimpleDateFormat with the best pattern generated above and the given locale
			SimpleDateFormat *sdf = new SimpleDateFormat(pattern,locales[j],status);
			dateReturned.remove();
			// Get the format of the given date
			sdf->format(date,dateReturned,status);
			/* write Unicode string to file */
			u_fprintf(f, "%-20S", dateReturned.getTerminatedBuffer());
			delete dtfg;
			delete sdf;
		} 
		u_fprintf(f,"\n");
	}
	/* close the file resource */
	u_fclose(f);
	delete cal;
	//! [getBestPatternExample]
}
Example #8
0
static void replaceFieldTypesExample() {
		// Use repalceFieldTypes API to replace zone 'zzzz' with 'vvvv'
       u_printf("========================================================================\n");
       u_printf(" replaceFieldTypeExample()\n");
       u_printf("\n");
       u_printf(" Use replaceFieldTypes API to replace zone 'zzzz' with 'vvvv'\n");
       u_printf("========================================================================\n");
	   //! [replaceFieldTypesExample]
		UFILE *out = u_finit(stdout, NULL, "UTF-8");
		UErrorCode status =U_ZERO_ERROR;
		UnicodeString pattern,dateReturned;
		Locale locale =Locale::getFrance();
		Calendar *cal = Calendar::createInstance(status);
		cal->set (1999,9,13,23,58,59);
		UDate date = cal->getTime(status);
		TimeZone *zone = TimeZone::createTimeZone(UnicodeString("Europe/Paris"));
		DateTimePatternGenerator *dtfg = DateTimePatternGenerator::createInstance(locale,status);
	    SimpleDateFormat *sdf = new SimpleDateFormat("EEEE d MMMM y HH:mm:ss zzzz",locale,status);
		sdf->setTimeZone(*zone);
		pattern = sdf->toPattern(pattern);
		u_fprintf(out, "%S\n", UnicodeString("Pattern before replacement:").getTerminatedBuffer());
      	u_fprintf(out, "%S\n", pattern.getTerminatedBuffer());
		dateReturned.remove();
		dateReturned = sdf->format(date, dateReturned, status);
		u_fprintf(out, "%S\n", UnicodeString("Date/Time format in fr_FR:").getTerminatedBuffer());
		u_fprintf(out, "%S\n", dateReturned.getTerminatedBuffer());
        // Replace zone "zzzz" in the pattern with "vvvv"
		UnicodeString newPattern = dtfg->replaceFieldTypes(pattern, "vvvv", status);
		// Apply the new pattern
		sdf->applyPattern(newPattern);
		dateReturned.remove();
		dateReturned = sdf->format(date, dateReturned, status);
		u_fprintf(out, "%S\n", UnicodeString("Pattern after replacement:").getTerminatedBuffer());
     	u_fprintf(out, "%S\n", newPattern.getTerminatedBuffer());
     	u_fprintf(out, "%S\n", UnicodeString("Date/Time format in fr_FR:").getTerminatedBuffer());
		u_fprintf(out, "%S\n", dateReturned.getTerminatedBuffer());
		delete sdf;
		delete dtfg;
		delete zone;
		delete cal;
		u_fclose(out);

		//! [replaceFieldTypesExample]
		/* output of the sample code:
        *************************************************************************************************
         Pattern before replacement:
         EEEE d MMMM y HH:mm:ss zzzz
         Date/Time format in fr_FR:
         jeudi 14 octobre 1999 05:58:59 heure avancée d’Europe centrale
         Pattern after replacement:
         EEEE d MMMM y HH:mm:ss vvvv
         Date/Time format in fr_FR:
         jeudi 14 octobre 1999 05:58:59 heure de l’Europe centrale

        *************************************************************************************************/
    }
Example #9
0
int main(int argc, char **argv) {

    Calendar *cal;
    TimeZone *zone;
    DateFormat *fmt;
    UErrorCode status = U_ZERO_ERROR;
    UnicodeString str;
    UDate date;

    // The languages in which we will display the date
    static char* LANGUAGE[] = {
        "en", "de", "fr"
    };
    static const int32_t N_LANGUAGE = sizeof(LANGUAGE)/sizeof(LANGUAGE[0]);

    // The time zones in which we will display the time
    static char* TIMEZONE[] = {
        "America/Los_Angeles",
        "America/New_York",
        "Europe/Paris",
        "Europe/Berlin"
    };
    static const int32_t N_TIMEZONE = sizeof(TIMEZONE)/sizeof(TIMEZONE[0]);

    // Create a calendar
    cal = Calendar::createInstance(status);
    check(status, "Calendar::createInstance");
    zone = createZone("GMT"); // Create a GMT zone
    cal->adoptTimeZone(zone);
    cal->clear();
    cal->set(1999, Calendar::JUNE, 4);
    date = cal->getTime(status);
    check(status, "Calendar::getTime");

    for (int32_t i=0; i<N_LANGUAGE; ++i) {
        Locale loc(LANGUAGE[i]);

        // Create a formatter for DATE
        fmt = DateFormat::createDateInstance(DateFormat::kFull, loc);
            
        // Format the date
        str.remove();
        fmt->format(date, str, status);
        
        // Display the formatted date string
        printf("Date (%s): ", LANGUAGE[i]);
        uprintf(escape(str));
        printf("\n\n");
    }

    printf("Exiting successfully\n");
    return 0;
}
int TimezoneUtils::offsetFromUtcToTz(QDateTime date, QString timezoneId, bool ignoreDstOffset, bool* error)
{
    int offset = 0;
    UErrorCode errorCode = U_ZERO_ERROR;

    // get timezone object
    TimeZone* tz = TimeZone::createTimeZone(reinterpret_cast<UChar*>(timezoneId.data()));
    if (!tz) {
        *error = true;
        return 0;
    }

    UnicodeString name;
    tz->getDisplayName(name);

    // get offset
    // cal takes ownership of tz - tried to delete it and got an error
    Calendar* cal = Calendar::createInstance(tz, errorCode);
    if (!cal || errorCode > 0) {
        *error = true;
        return 0;
    }
    cal->set(date.date().year(), date.date().month(), date.date().day(), date.time().hour(), date.time().minute());
    UDate udate = cal->getTime(errorCode);
    if (errorCode > 0) {
        *error = true;
        delete cal;
        return 0;
    }

    UBool isGmt = false;
    int32_t rawOffset = 0;
    int32_t dstOffset = 0;
    tz->getOffset(udate, isGmt, rawOffset, dstOffset, errorCode);
    if (errorCode > 0) {
        *error = true;
        delete cal;
        return 0;
    }

    if (!ignoreDstOffset) {
        offset = rawOffset + dstOffset;
    } else {
        offset = rawOffset;
    }
    delete cal;

    offset /= 1000;
    *error = false;

    return offset;
}
Example #11
0
// Utility methods to create a date.  This is useful for converting Java constructs
// which create a Date object.
UDate
CalendarTimeZoneTest::date(int32_t y, int32_t m, int32_t d, int32_t hr, int32_t min, int32_t sec)
{
    Calendar* cal = getCalendar();
    if (cal == 0) return 0.0;
    cal->clear();
    cal->set(1900 + y, m, d, hr, min, sec); // Add 1900 to follow java.util.Date protocol
    UErrorCode status = U_ZERO_ERROR;
    UDate dt = cal->getTime(status);
    releaseCalendar(cal);
    if (U_FAILURE(status))
    {
        errln("FAIL: Calendar::getTime failed: %s", u_errorName(status));
        return 0.0;
    }
    return dt;
}
/**
 * Verify that TaiWanCalendar shifts years to Minguo Era but otherwise
 * behaves like GregorianCalendar.
 */
void IntlCalendarTest::TestTaiwan() {
    // MG 1 == 1912 AD
    UDate timeA = Calendar::getNow();
    
    // TODO port these to the data items
    int32_t data[] = {
        1,           // B. era   [928479600000]
        1,        // B. year
        1912,        // G. year
        UCAL_JUNE,   // month
        4,           // day

        1,           // B. era   [-79204842000000]
        3,           // B. year
        1914,        // G. year
        UCAL_FEBRUARY, // month
        12,          // day

        1,           // B. era   [-79204842000000]
        96,           // B. year
        2007,        // G. year
        UCAL_FEBRUARY, // month
        12,          // day

        -1,-1,-1,-1,-1,-1,-1,-1,-1,-1
    };
    Calendar *cal;
    UErrorCode status = U_ZERO_ERROR;
    cal = Calendar::createInstance("en_US@calendar=roc", status);
    CHECK(status, UnicodeString("Creating en_US@calendar=roc calendar"));

    // Sanity check the calendar 
    UDate timeB = Calendar::getNow();
    UDate timeCal = cal->getTime(status);

    if(!(timeA <= timeCal) || !(timeCal <= timeB)) {
      errln((UnicodeString)"Error: Calendar time " + timeCal +
            " is not within sampled times [" + timeA + " to " + timeB + "]!");
    }
    // end sanity check


    quasiGregorianTest(*cal,Locale("en_US"),data);
    delete cal;
}
/**
 * Verify that JapaneseCalendar shifts years to Japanese Eras but otherwise
 * behaves like GregorianCalendar.
 */
void IntlCalendarTest::TestJapanese() {
    UDate timeA = Calendar::getNow();
    
    /* Sorry.. japancal.h is private! */
#define JapaneseCalendar_MEIJI  232
#define JapaneseCalendar_TAISHO 233
#define JapaneseCalendar_SHOWA  234
#define JapaneseCalendar_HEISEI 235
    
    // BE 2542 == 1999 CE
    int32_t data[] = { 
        //       Jera         Jyr  Gyear   m             d
        JapaneseCalendar_MEIJI, 1, 1868, UCAL_SEPTEMBER, 8,
        JapaneseCalendar_MEIJI, 1, 1868, UCAL_SEPTEMBER, 9,
        JapaneseCalendar_MEIJI, 2, 1869, UCAL_JUNE, 4,
        JapaneseCalendar_MEIJI, 45, 1912, UCAL_JULY, 29,
        JapaneseCalendar_TAISHO, 1, 1912, UCAL_JULY, 30,
        JapaneseCalendar_TAISHO, 1, 1912, UCAL_AUGUST, 1,
        
        // new tests (not in java)
        JapaneseCalendar_SHOWA,     64,   1989,  UCAL_JANUARY, 7,  // Test current era transition (different code path than others)
        JapaneseCalendar_HEISEI,    1,   1989,  UCAL_JANUARY, 8,   
        JapaneseCalendar_HEISEI,    1,   1989,  UCAL_JANUARY, 9,
        JapaneseCalendar_HEISEI,    1,   1989,  UCAL_DECEMBER, 20,
        JapaneseCalendar_HEISEI,  15,  2003,  UCAL_MAY, 22,
        -1,-1,-1,-1,-1,-1,-1,-1,-1,-1
    };
    
    Calendar *cal;
    UErrorCode status = U_ZERO_ERROR;
    cal = Calendar::createInstance("ja_JP@calendar=japanese", status);
    CHECK(status, UnicodeString("Creating ja_JP@calendar=japanese calendar"));
    // Sanity check the calendar 
    UDate timeB = Calendar::getNow();
    UDate timeCal = cal->getTime(status);

    if(!(timeA <= timeCal) || !(timeCal <= timeB)) {
      errln((UnicodeString)"Error: Calendar time " + timeCal +
            " is not within sampled times [" + timeA + " to " + timeB + "]!");
    }
    // end sanity check
    quasiGregorianTest(*cal,Locale("ja_JP"),data);
    delete cal;
}
/**
 * Verify that BuddhistCalendar shifts years to Buddhist Era but otherwise
 * behaves like GregorianCalendar.
 */
void IntlCalendarTest::TestBuddhist() {
    // BE 2542 == 1999 CE
    UDate timeA = Calendar::getNow();

    int32_t data[] = {
        0,           // B. era   [928479600000]
        2542,        // B. year
        1999,        // G. year
        UCAL_JUNE,   // month
        4,           // day

        0,           // B. era   [-79204842000000]
        3,           // B. year
        -540,        // G. year
        UCAL_FEBRUARY, // month
        12,          // day

        0,           // test month calculation:  4795 BE = 4252 AD is a leap year, but 4795 AD is not.
        4795,        // BE [72018057600000]
        4252,        // AD
        UCAL_FEBRUARY,
        29,

        -1,-1,-1,-1,-1,-1,-1,-1,-1,-1
    };
    Calendar *cal;
    UErrorCode status = U_ZERO_ERROR;
    cal = Calendar::createInstance("th_TH@calendar=buddhist", status);
    CHECK(status, UnicodeString("Creating th_TH@calendar=buddhist calendar"));

    // Sanity check the calendar 
    UDate timeB = Calendar::getNow();
    UDate timeCal = cal->getTime(status);

    if(!(timeA <= timeCal) || !(timeCal <= timeB)) {
      errln((UnicodeString)"Error: Calendar time " + timeCal +
            " is not within sampled times [" + timeA + " to " + timeB + "]!");
    }
    // end sanity check


    quasiGregorianTest(*cal,Locale("th_TH@calendar=gregorian"),data);
    delete cal;
}
Example #15
0
void IntlCalendarTest::TestPersian() {
    UDate timeA = Calendar::getNow();
    
    Calendar *cal;
    UErrorCode status = U_ZERO_ERROR;
    cal = Calendar::createInstance("fa_IR@calendar=persian", status);
    CHECK(status, UnicodeString("Creating fa_IR@calendar=persian calendar"));
    // Sanity check the calendar 
    UDate timeB = Calendar::getNow();
    UDate timeCal = cal->getTime(status);

    if(!(timeA <= timeCal) || !(timeCal <= timeB)) {
      errln((UnicodeString)"Error: Calendar time " + timeCal +
            " is not within sampled times [" + timeA + " to " + timeB + "]!");
    }
    // end sanity check
// quasiGregorianTest(*cal,Locale("ja_JP"),data);
    delete cal;
}
Example #16
0
static void addPatternExample() {
		
		u_printf("========================================================================\n");
        u_printf(" addPatternExample()\n");
		u_printf("\n");
        u_printf(" Use addPattern API to add new '. von' to existing pattern\n");
        u_printf("========================================================================\n");
		//! [addPatternExample]
		UErrorCode status =U_ZERO_ERROR;
		UnicodeString conflictingPattern,dateReturned, pattern;
		Locale locale=Locale::getFrance();
		Calendar *cal = Calendar::createInstance(status);
		cal->set (1999,9,13,23,58,59);
		UDate date = cal->getTime(status);
        // Create an DateTimePatternGenerator instance for the given locale
		DateTimePatternGenerator *dtfg= DateTimePatternGenerator::createInstance(locale,status);
		SimpleDateFormat *sdf = new SimpleDateFormat(dtfg->getBestPattern("MMMMddHmm",status),locale,status);
        // Add '. von' to the existing pattern
        dtfg->addPattern("dd'. von' MMMM", true, conflictingPattern,status);
        // Apply the new pattern
        sdf->applyPattern(dtfg->getBestPattern("MMMMddHmm",status));
		dateReturned = sdf->format(date, dateReturned, status);
		pattern =sdf->toPattern(pattern);
		u_printf("%s\n", "New Pattern for FRENCH: ");
      	u_printf("%S\n", pattern.getTerminatedBuffer());
		u_printf("%s\n", "Date Time in new Pattern: ");
		u_printf("%S\n", dateReturned.getTerminatedBuffer());
		delete dtfg;
		delete sdf;
		delete cal;

		//! [addPatternExample]
        /* output of the sample code:
        ************************************************************************************************
         New Pattern for FRENCH: dd. 'von' MMMM HH:mm
         Date Time in new Pattern: 13. von octobre 23:58
     
        *************************************************************************************************/
 	}
Example #17
0
/**
    * 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 TimeZoneBoundaryTest::verifyMapping(Calendar& cal, int year, int month, int dom, int hour,
                    double epochHours) {
    double H = 3600000.0;
    UErrorCode status = U_ZERO_ERROR;
    cal.clear();
    cal.set(year, month, dom, hour, 0, 0);
    UDate e = cal.getTime(status)/ H;
    UDate ed = (epochHours * H);
    if (e == epochHours) {
        logln(UnicodeString("Ok: ") + year + "/" + (month+1) + "/" + dom + " " + hour + ":00 => " +
                e + " (" + ed + ")");
    } else {
        dataerrln(UnicodeString("FAIL: ") + year + "/" + (month+1) + "/" + dom + " " + hour + ":00 => " +
                e + " (" + (e * H) + ")" +
                ", expected " + epochHours + " (" + ed + ")");
    }
    cal.setTime(ed, status);
    if (cal.get(UCAL_YEAR, status) == year &&
        cal.get(UCAL_MONTH, status) == month &&
        cal.get(UCAL_DATE, status) == dom &&
        cal.get(UCAL_MILLISECONDS_IN_DAY, status) == hour * 3600000) {
        logln(UnicodeString("Ok: ") + epochHours + " (" + ed + ") => " +
                cal.get(UCAL_YEAR, status) + "/" +
                (cal.get(UCAL_MONTH, status)+1) + "/" +
                cal.get(UCAL_DATE, status) + " " +
                cal.get(UCAL_MILLISECOND, status)/H);
    } else {
        dataerrln(UnicodeString("FAIL: ") + epochHours + " (" + ed + ") => " +
                cal.get(UCAL_YEAR, status) + "/" +
                (cal.get(UCAL_MONTH, status)+1) + "/" +
                cal.get(UCAL_DATE, status) + " " +
                cal.get(UCAL_MILLISECOND, status)/H +
                ", expected " + year + "/" + (month+1) + "/" + dom +
                " " + hour);
    }
}
Example #18
0
void DataDrivenFormatTest::testConvertDate(TestData *testData,
        const DataMap * /* settings */, UBool fmt) {
    UnicodeString kPATTERN("PATTERN="); // TODO: static
    UnicodeString kMILLIS("MILLIS="); // TODO: static
    UnicodeString kRELATIVE_MILLIS("RELATIVE_MILLIS="); // TODO: static
    UnicodeString kRELATIVE_ADD("RELATIVE_ADD:"); // TODO: static

    UErrorCode status = U_ZERO_ERROR;
    SimpleDateFormat basicFmt(UnicodeString("EEE MMM dd yyyy / YYYY'-W'ww-ee"),
                              status);
    if (U_FAILURE(status)) {
        dataerrln("FAIL: Couldn't create basic SimpleDateFormat: %s",
                  u_errorName(status));
        return;
    }

    const DataMap *currentCase= NULL;
    // Start the processing
    int n = 0;
    while (testData->nextCase(currentCase, status)) {
        char calLoc[256] = "";
        DateTimeStyleSet styleSet;
        UnicodeString pattern;
        UBool usePattern = FALSE;
        (void)usePattern;   // Suppress unused warning.
        CalendarFieldsSet fromSet;
        UDate fromDate = 0;
        UBool useDate = FALSE;

        UDate now = Calendar::getNow();

        ++n;

        char theCase[200];
        sprintf(theCase, "case %d:", n);
        UnicodeString caseString(theCase, "");

        // load params
        UnicodeString locale = currentCase->getString("locale", status);
        if (U_FAILURE(status)) {
            errln("case %d: No 'locale' line.", n);
            continue;
        }
        UnicodeString zone = currentCase->getString("zone", status);
        if (U_FAILURE(status)) {
            errln("case %d: No 'zone' line.", n);
            continue;
        }
        UnicodeString spec = currentCase->getString("spec", status);
        if(U_FAILURE(status)) {
            errln("case %d: No 'spec' line.", n);
            continue;
        }
        UnicodeString date = currentCase->getString("date", status);
        if(U_FAILURE(status)) {
            errln("case %d: No 'date' line.", n);
            continue;
        }
        UnicodeString expectStr= currentCase->getString("str", status);
        if(U_FAILURE(status)) {
            errln("case %d: No 'str' line.", n);
            continue;
        }

        DateFormat *format = NULL;

        // Process: 'locale'
        locale.extract(0, locale.length(), calLoc, (const char*)0); // default codepage.  Invariant codepage doesn't have '@'!
        Locale loc(calLoc);
        if(spec.startsWith(kPATTERN)) {
            pattern = UnicodeString(spec,kPATTERN.length());
            usePattern = TRUE;
            format = new SimpleDateFormat(pattern, loc, status);
            if(U_FAILURE(status)) {
                errln("case %d: could not create SimpleDateFormat from pattern: %s", n, u_errorName(status));
                continue;
            }
        } else {
            if(styleSet.parseFrom(spec, status)<0 || U_FAILURE(status)) {
                errln("case %d: could not parse spec as style fields: %s", n, u_errorName(status));
                continue;
            }
            format = DateFormat::createDateTimeInstance((DateFormat::EStyle)styleSet.getDateStyle(), (DateFormat::EStyle)styleSet.getTimeStyle(), loc);
            if(format == NULL ) {
                errln("case %d: could not create SimpleDateFormat from styles.", n);
                continue;
            }
        }

        Calendar *cal = Calendar::createInstance(loc, status);
        if(U_FAILURE(status)) {
            errln("case %d: could not create calendar from %s", n, calLoc);
        }

        if (zone.length() > 0) {
            TimeZone * tz = TimeZone::createTimeZone(zone);
            cal->setTimeZone(*tz);
            format->setTimeZone(*tz);
            delete tz;
        }

        // parse 'date'
        if(date.startsWith(kMILLIS)) {
            UnicodeString millis = UnicodeString(date, kMILLIS.length());
            useDate = TRUE;
            fromDate = udbg_stod(millis);
        } else if(date.startsWith(kRELATIVE_MILLIS)) {
            UnicodeString millis = UnicodeString(date, kRELATIVE_MILLIS.length());
            useDate = TRUE;
            fromDate = udbg_stod(millis) + now;
        } else if(date.startsWith(kRELATIVE_ADD)) {
            UnicodeString add = UnicodeString(date, kRELATIVE_ADD.length());  // "add" is a string indicating which fields to add
            if(fromSet.parseFrom(add, status)<0 || U_FAILURE(status)) {
                errln("case %d: could not parse date as RELATIVE_ADD calendar fields: %s", n, u_errorName(status));
                continue;
            }
            useDate=TRUE;
            cal->clear();
            cal->setTime(now, status);
            for (int q=0; q<UCAL_FIELD_COUNT; q++) {
                if (fromSet.isSet((UCalendarDateFields)q)) {
                    //int32_t oldv = cal->get((UCalendarDateFields)q, status);
                    if (q == UCAL_DATE) {
                        cal->add((UCalendarDateFields)q,
                                 fromSet.get((UCalendarDateFields)q), status);
                    } else {
                        cal->set((UCalendarDateFields)q,
                                 fromSet.get((UCalendarDateFields)q));
                    }
                    //int32_t newv = cal->get((UCalendarDateFields)q, status);
                }
            }
            fromDate = cal->getTime(status);
            if(U_FAILURE(status)) {
                errln("case %d: could not apply date as RELATIVE_ADD calendar fields: %s", n, u_errorName(status));
                continue;
            }
        } else if(fromSet.parseFrom(date, status)<0 || U_FAILURE(status)) {
            errln("case %d: could not parse date as calendar fields: %s", n, u_errorName(status));
            continue;
        }

        // now, do it.
        if (fmt) {
            FieldPosition pos;
//            logln((UnicodeString)"#"+n+" "+locale+"/"+from+" >>> "+toCalLoc+"/"
//                    +to);
            cal->clear();
            UnicodeString output;
            output.remove();

            if(useDate) {
//                cal->setTime(fromDate, status);
//                if(U_FAILURE(status)) {
//                    errln("case %d: could not set time on calendar: %s", n, u_errorName(status));
//                    continue;
//                }
                format->format(fromDate, output, pos, status);
            } else {
                fromSet.setOnCalendar(cal, status);
                if(U_FAILURE(status)) {
                    errln("case %d: could not set fields on calendar: %s", n, u_errorName(status));
                    continue;
                }
                format->format(*cal, output, pos);
            }

            // check erro result from 'format'
            if(U_FAILURE(status)) {
                errln("case %d: could not format(): %s", n, u_errorName(status)); // TODO: use 'pos'
            }
//            if(pos.getBeginIndex()==0 && pos.getEndIndex()==0) { // TODO: more precise error?
//                errln("WARNING: case %d: format's pos returned (0,0) - error ??", n);
//            }

            if(output == expectStr) {
                logln(caseString+": format: SUCCESS! "+UnicodeString("expect=output=")+output);
            } else {
                UnicodeString result;
                UnicodeString result2;
                errln(caseString+": format:  output!=expectStr, got " + *udbg_escape(output, &result) + " expected " + *udbg_escape(expectStr, &result2));
            }
        } else {
            cal->clear();
            ParsePosition pos;
            format->parse(expectStr,*cal,pos);
            if(useDate) {
                UDate gotDate = cal->getTime(status);
                if(U_FAILURE(status)) {
                    errln(caseString+": parse: could not get time on calendar: "+UnicodeString(u_errorName(status)));
                    continue;
                }
                if(gotDate == fromDate) {
                    logln(caseString+": parse: SUCCESS! "+UnicodeString("gotDate=parseDate=")+expectStr);
                } else {
                    UnicodeString expectDateStr, gotDateStr;
                    basicFmt.format(fromDate,expectDateStr);
                    basicFmt.format(gotDate,gotDateStr);
                    errln(caseString+": parse: FAIL. parsed '"+expectStr+"' and got "+gotDateStr+", expected " + expectDateStr);
                }
            } else {
//                Calendar *cal2 = cal->clone();
//                cal2->clear();
//                fromSet.setOnCalendar(cal2, status);
                if(U_FAILURE(status)) {
                    errln("case %d: parse: could not set fields on calendar: %s", n, u_errorName(status));
                    continue;
                }

                CalendarFieldsSet diffSet;
//                diffSet.clear();
                if (!fromSet.matches(cal, diffSet, status)) {
                    UnicodeString diffs = diffSet.diffFrom(fromSet, status);
                    errln((UnicodeString)"FAIL: "+caseString
                          +", Differences: '"+ diffs
                          +"', status: "+ u_errorName(status));
                } else if (U_FAILURE(status)) {
                    errln("FAIL: "+caseString+" parse SET SOURCE calendar Failed to match: "
                          +u_errorName(status));
                } else {
                    logln("PASS: "******" parse.");
                }



            }
        }
        delete cal;
        delete format;

    }
//    delete basicFmt;
}
/**
 * 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, ...  ... , -1 }
 */
void IntlCalendarTest::quasiGregorianTest(Calendar& cal, const Locale& gcl, const int32_t *data) {
  UErrorCode status = U_ZERO_ERROR;
  // 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::createInstance(gcl, status);
  if (U_FAILURE(status)) {
    dataerrln("Error calling Calendar::createInstance"); 
    return;
  }

  int32_t tz1 = cal.get(UCAL_ZONE_OFFSET,status);
  int32_t tz2 = grego -> get (UCAL_ZONE_OFFSET, status);
  if(tz1 != tz2) { 
    errln((UnicodeString)"cal's tz " + tz1 + " != grego's tz " + tz2);
  }

  for (int32_t i=0; data[i]!=-1; ) {
    int32_t era = data[i++];
    int32_t year = data[i++];
    int32_t gregorianYear = data[i++];
    int32_t month = data[i++];
    int32_t dayOfMonth = data[i++];
    
    grego->clear();
    grego->set(gregorianYear, month, dayOfMonth);
    UDate D = grego->getTime(status);
    
    cal.clear();
    cal.set(UCAL_ERA, era);
    cal.set(year, month, dayOfMonth);
    UDate d = cal.getTime(status);
#ifdef U_DEBUG_DUMPCALS
    logln((UnicodeString)"cal  : " + CalendarTest::calToStr(cal));
    logln((UnicodeString)"grego: " + CalendarTest::calToStr(*grego));
#endif
    if (d == D) {
      logln(UnicodeString("OK: ") + era + ":" + year + "/" + (month+1) + "/" + dayOfMonth +
            " => " + d + " (" + UnicodeString(cal.getType()) + ")");
    } else {
      errln(UnicodeString("Fail: (fields to millis)") + era + ":" + year + "/" + (month+1) + "/" + dayOfMonth +
            " => " + d + ", expected " + D + " (" + UnicodeString(cal.getType()) + "Off by: " + (d-D));
    }
    
    // Now, set the gregorian millis on the other calendar
    cal.clear();
    cal.setTime(D, status);
    int e = cal.get(UCAL_ERA, status);
    int y = cal.get(UCAL_YEAR, status);
#ifdef U_DEBUG_DUMPCALS
    logln((UnicodeString)"cal  : " + CalendarTest::calToStr(cal));
    logln((UnicodeString)"grego: " + CalendarTest::calToStr(*grego));
#endif
    if (y == year && e == era) {
      logln((UnicodeString)"OK: " + D + " => " + cal.get(UCAL_ERA, status) + ":" +
            cal.get(UCAL_YEAR, status) + "/" +
            (cal.get(UCAL_MONTH, status)+1) + "/" + cal.get(UCAL_DATE, status) +  " (" + UnicodeString(cal.getType()) + ")");
    } else {
      errln((UnicodeString)"Fail: (millis to fields)" + D + " => " + cal.get(UCAL_ERA, status) + ":" +
            cal.get(UCAL_YEAR, status) + "/" +
            (cal.get(UCAL_MONTH, status)+1) + "/" + cal.get(UCAL_DATE, status) +
            ", expected " + era + ":" + year + "/" + (month+1) + "/" +
            dayOfMonth +  " (" + UnicodeString(cal.getType()));
    }
  }
  delete grego;
  CHECK(status, "err during quasiGregorianTest()");
}
/*
 * Testing getOffset APIs around rule transition by local standard/wall time.
 */
void
TimeZoneOffsetLocalTest::TestGetOffsetAroundTransition() {
    const int32_t NUM_DATES = 10;
    const int32_t NUM_TIMEZONES = 3;

    const int32_t HOUR = 60*60*1000;
    const int32_t MINUTE = 60*1000;

    const int32_t DATES[NUM_DATES][6] = {
        {2006, UCAL_APRIL, 2, 1, 30, 1*HOUR+30*MINUTE},
        {2006, UCAL_APRIL, 2, 2, 00, 2*HOUR},
        {2006, UCAL_APRIL, 2, 2, 30, 2*HOUR+30*MINUTE},
        {2006, UCAL_APRIL, 2, 3, 00, 3*HOUR},
        {2006, UCAL_APRIL, 2, 3, 30, 3*HOUR+30*MINUTE},
        {2006, UCAL_OCTOBER, 29, 0, 30, 0*HOUR+30*MINUTE},
        {2006, UCAL_OCTOBER, 29, 1, 00, 1*HOUR},
        {2006, UCAL_OCTOBER, 29, 1, 30, 1*HOUR+30*MINUTE},
        {2006, UCAL_OCTOBER, 29, 2, 00, 2*HOUR},
        {2006, UCAL_OCTOBER, 29, 2, 30, 2*HOUR+30*MINUTE},
    };

    // Expected offsets by int32_t getOffset(uint8_t era, int32_t year, int32_t month, int32_t day,
    // uint8_t dayOfWeek, int32_t millis, UErrorCode& status)
    const int32_t OFFSETS1[NUM_DATES] = {
        // April 2, 2006
        -8*HOUR,
        -7*HOUR,
        -7*HOUR,
        -7*HOUR,
        -7*HOUR,

        // October 29, 2006
        -7*HOUR,
        -8*HOUR,
        -8*HOUR,
        -8*HOUR,
        -8*HOUR,
    };

    // Expected offsets by void getOffset(UDate date, UBool local, int32_t& rawOffset,
    // int32_t& dstOffset, UErrorCode& ec) with local=TRUE
    // or void getOffsetFromLocal(UDate date, int32_t nonExistingTimeOpt, int32_t duplicatedTimeOpt,
    // int32_t& rawOffset, int32_t& dstOffset, UErrorCode& status) with
    // nonExistingTimeOpt=kStandard/duplicatedTimeOpt=kStandard
    const int32_t OFFSETS2[NUM_DATES][2] = {
        // April 2, 2006
        {-8*HOUR, 0},
        {-8*HOUR, 0},
        {-8*HOUR, 0},
        {-8*HOUR, 1*HOUR},
        {-8*HOUR, 1*HOUR},

        // Oct 29, 2006
        {-8*HOUR, 1*HOUR},
        {-8*HOUR, 0},
        {-8*HOUR, 0},
        {-8*HOUR, 0},
        {-8*HOUR, 0},
    };

    // Expected offsets by void getOffsetFromLocal(UDate date, int32_t nonExistingTimeOpt,
    // int32_t duplicatedTimeOpt, int32_t& rawOffset, int32_t& dstOffset, UErrorCode& status) with
    // nonExistingTimeOpt=kDaylight/duplicatedTimeOpt=kDaylight
    const int32_t OFFSETS3[][2] = {
        // April 2, 2006
        {-8*HOUR, 0},
        {-8*HOUR, 1*HOUR},
        {-8*HOUR, 1*HOUR},
        {-8*HOUR, 1*HOUR},
        {-8*HOUR, 1*HOUR},

        // October 29, 2006
        {-8*HOUR, 1*HOUR},
        {-8*HOUR, 1*HOUR},
        {-8*HOUR, 1*HOUR},
        {-8*HOUR, 0},
        {-8*HOUR, 0},
    };

    UErrorCode status = U_ZERO_ERROR;

    int32_t rawOffset, dstOffset;
    TimeZone* utc = TimeZone::createTimeZone("UTC");
    Calendar* cal = Calendar::createInstance(*utc, status);
    if (U_FAILURE(status)) {
        errln("Calendar::createInstance failed");
        return;
    }
    cal->clear();

    // Set up TimeZone objects - OlsonTimeZone, SimpleTimeZone and RuleBasedTimeZone
    BasicTimeZone *TESTZONES[NUM_TIMEZONES];

    TESTZONES[0] = (BasicTimeZone*)TimeZone::createTimeZone("America/Los_Angeles");
    TESTZONES[1] = new SimpleTimeZone(-8*HOUR, "Simple Pacific Time",
                                        UCAL_APRIL, 1, UCAL_SUNDAY, 2*HOUR,
                                        UCAL_OCTOBER, -1, UCAL_SUNDAY, 2*HOUR, status);
    if (U_FAILURE(status)) {
        errln("SimpleTimeZone constructor failed");
        return;
    }

    InitialTimeZoneRule *ir = new InitialTimeZoneRule(
            "Pacific Standard Time", // Initial time Name
            -8*HOUR,        // Raw offset
            0*HOUR);        // DST saving amount

    RuleBasedTimeZone *rbPT = new RuleBasedTimeZone("Rule based Pacific Time", ir);

    DateTimeRule *dtr;
    AnnualTimeZoneRule *atzr;
    const int32_t STARTYEAR = 2000;

    dtr = new DateTimeRule(UCAL_APRIL, 1, UCAL_SUNDAY,
                        2*HOUR, DateTimeRule::WALL_TIME); // 1st Sunday in April, at 2AM wall time
    atzr = new AnnualTimeZoneRule("Pacific Daylight Time",
            -8*HOUR /* rawOffset */, 1*HOUR /* dstSavings */, dtr,
            STARTYEAR, AnnualTimeZoneRule::MAX_YEAR);
    rbPT->addTransitionRule(atzr, status);
    if (U_FAILURE(status)) {
        errln("Could not add DST start rule to the RuleBasedTimeZone rbPT");
        return;
    }

    dtr = new DateTimeRule(UCAL_OCTOBER, -1, UCAL_SUNDAY,
                        2*HOUR, DateTimeRule::WALL_TIME); // last Sunday in October, at 2AM wall time
    atzr = new AnnualTimeZoneRule("Pacific Standard Time",
            -8*HOUR /* rawOffset */, 0 /* dstSavings */, dtr,
            STARTYEAR, AnnualTimeZoneRule::MAX_YEAR);
    rbPT->addTransitionRule(atzr, status);
    if (U_FAILURE(status)) {
        errln("Could not add STD start rule to the RuleBasedTimeZone rbPT");
        return;
    }

    rbPT->complete(status);
    if (U_FAILURE(status)) {
        errln("complete() failed for RuleBasedTimeZone rbPT");
        return;
    }

    TESTZONES[2] = rbPT;

    // Calculate millis
    UDate MILLIS[NUM_DATES];
    for (int32_t i = 0; i < NUM_DATES; i++) {
        cal->clear();
        cal->set(DATES[i][0], DATES[i][1], DATES[i][2], DATES[i][3], DATES[i][4]);
        MILLIS[i] = cal->getTime(status);
        if (U_FAILURE(status)) {
            errln("cal->getTime failed");
            return;
        }
    }

    SimpleDateFormat df(UnicodeString("yyyy-MM-dd HH:mm:ss"), status);
    if (U_FAILURE(status)) {
        errln("Failed to initialize a SimpleDateFormat");
    }
    df.setTimeZone(*utc);
    UnicodeString dateStr;

    // Test getOffset(uint8_t era, int32_t year, int32_t month, int32_t day,
    // uint8_t dayOfWeek, int32_t millis, UErrorCode& status)
    for (int32_t i = 0; i < NUM_TIMEZONES; i++) {
        for (int32_t d = 0; d < NUM_DATES; d++) {
            status = U_ZERO_ERROR;
            int32_t offset = TESTZONES[i]->getOffset(GregorianCalendar::AD, DATES[d][0], DATES[d][1], DATES[d][2],
                                                UCAL_SUNDAY, DATES[d][5], status);
            if (U_FAILURE(status)) {
                errln((UnicodeString)"getOffset(era,year,month,day,dayOfWeek,millis,status) failed for TESTZONES[" + i + "]");
            } else if (offset != OFFSETS1[d]) {
                dateStr.remove();
                df.format(MILLIS[d], dateStr);
                errln((UnicodeString)"Bad offset returned by TESTZONES[" + i + "] at "
                        + dateStr + "(standard) - Got: " + offset + " Expected: " + OFFSETS1[d]);
            }
        }
    }

    // Test getOffset(UDate date, UBool local, int32_t& rawOffset,
    // int32_t& dstOffset, UErrorCode& ec) with local = TRUE
    for (int32_t i = 0; i < NUM_TIMEZONES; i++) {
        for (int32_t m = 0; m < NUM_DATES; m++) {
            status = U_ZERO_ERROR;
            TESTZONES[i]->getOffset(MILLIS[m], TRUE, rawOffset, dstOffset, status);
            if (U_FAILURE(status)) {
                errln((UnicodeString)"getOffset(date,local,rawOfset,dstOffset,ec) failed for TESTZONES[" + i + "]");
            } else if (rawOffset != OFFSETS2[m][0] || dstOffset != OFFSETS2[m][1]) {
                dateStr.remove();
                df.format(MILLIS[m], dateStr);
                errln((UnicodeString)"Bad offset returned by TESTZONES[" + i + "] at "
                        + dateStr + "(wall) - Got: "
                        + rawOffset + "/" + dstOffset
                        + " Expected: " + OFFSETS2[m][0] + "/" + OFFSETS2[m][1]);
            }
        }
    }

    // Test getOffsetFromLocal(UDate date, int32_t nonExistingTimeOpt, int32_t duplicatedTimeOpt,
    // int32_t& rawOffset, int32_t& dstOffset, UErroCode& status)
    // with nonExistingTimeOpt=kStandard/duplicatedTimeOpt=kStandard
    for (int32_t i = 0; i < NUM_TIMEZONES; i++) {
        for (int m = 0; m < NUM_DATES; m++) {
            status = U_ZERO_ERROR;
            TESTZONES[i]->getOffsetFromLocal(MILLIS[m], BasicTimeZone::kStandard, BasicTimeZone::kStandard,
                rawOffset, dstOffset, status);
            if (U_FAILURE(status)) {
                errln((UnicodeString)"getOffsetFromLocal with kStandard/kStandard failed for TESTZONES[" + i + "]");
            } else if (rawOffset != OFFSETS2[m][0] || dstOffset != OFFSETS2[m][1]) {
                dateStr.remove();
                df.format(MILLIS[m], dateStr);
                errln((UnicodeString)"Bad offset returned by TESTZONES[" + i + "] at "
                        + dateStr + "(wall/kStandard/kStandard) - Got: "
                        + rawOffset + "/" + dstOffset
                        + " Expected: " + OFFSETS2[m][0] + "/" + OFFSETS2[m][1]);
            }
        }
    }

    // Test getOffsetFromLocal(UDate date, int32_t nonExistingTimeOpt, int32_t duplicatedTimeOpt,
    // int32_t& rawOffset, int32_t& dstOffset, UErroCode& status)
    // with nonExistingTimeOpt=kDaylight/duplicatedTimeOpt=kDaylight
    for (int32_t i = 0; i < NUM_TIMEZONES; i++) {
        for (int m = 0; m < NUM_DATES; m++) {
            status = U_ZERO_ERROR;
            TESTZONES[i]->getOffsetFromLocal(MILLIS[m], BasicTimeZone::kDaylight, BasicTimeZone::kDaylight,
                rawOffset, dstOffset, status);
            if (U_FAILURE(status)) {
                errln((UnicodeString)"getOffsetFromLocal with kDaylight/kDaylight failed for TESTZONES[" + i + "]");
            } else if (rawOffset != OFFSETS3[m][0] || dstOffset != OFFSETS3[m][1]) {
                dateStr.remove();
                df.format(MILLIS[m], dateStr);
                errln((UnicodeString)"Bad offset returned by TESTZONES[" + i + "] at "
                        + dateStr + "(wall/kDaylight/kDaylight) - Got: "
                        + rawOffset + "/" + dstOffset
                        + " Expected: " + OFFSETS3[m][0] + "/" + OFFSETS3[m][1]);
            }
        }
    }

    // Test getOffsetFromLocal(UDate date, int32_t nonExistingTimeOpt, int32_t duplicatedTimeOpt,
    // int32_t& rawOffset, int32_t& dstOffset, UErroCode& status)
    // with nonExistingTimeOpt=kFormer/duplicatedTimeOpt=kLatter
    for (int32_t i = 0; i < NUM_TIMEZONES; i++) {
        for (int m = 0; m < NUM_DATES; m++) {
            status = U_ZERO_ERROR;
            TESTZONES[i]->getOffsetFromLocal(MILLIS[m], BasicTimeZone::kFormer, BasicTimeZone::kLatter,
                rawOffset, dstOffset, status);
            if (U_FAILURE(status)) {
                errln((UnicodeString)"getOffsetFromLocal with kFormer/kLatter failed for TESTZONES[" + i + "]");
            } else if (rawOffset != OFFSETS2[m][0] || dstOffset != OFFSETS2[m][1]) {
                dateStr.remove();
                df.format(MILLIS[m], dateStr);
                errln((UnicodeString)"Bad offset returned by TESTZONES[" + i + "] at "
                        + dateStr + "(wall/kFormer/kLatter) - Got: "
                        + rawOffset + "/" + dstOffset
                        + " Expected: " + OFFSETS2[m][0] + "/" + OFFSETS2[m][1]);
            }
        }
    }

    // Test getOffsetFromLocal(UDate date, int32_t nonExistingTimeOpt, int32_t duplicatedTimeOpt,
    // int32_t& rawOffset, int32_t& dstOffset, UErroCode& status)
    // with nonExistingTimeOpt=kLatter/duplicatedTimeOpt=kFormer
    for (int32_t i = 0; i < NUM_TIMEZONES; i++) {
        for (int m = 0; m < NUM_DATES; m++) {
            status = U_ZERO_ERROR;
            TESTZONES[i]->getOffsetFromLocal(MILLIS[m], BasicTimeZone::kLatter, BasicTimeZone::kFormer,
                rawOffset, dstOffset, status);
            if (U_FAILURE(status)) {
                errln((UnicodeString)"getOffsetFromLocal with kLatter/kFormer failed for TESTZONES[" + i + "]");
            } else if (rawOffset != OFFSETS3[m][0] || dstOffset != OFFSETS3[m][1]) {
                dateStr.remove();
                df.format(MILLIS[m], dateStr);
                errln((UnicodeString)"Bad offset returned by TESTZONES[" + i + "] at "
                        + dateStr + "(wall/kLatter/kFormer) - Got: "
                        + rawOffset + "/" + dstOffset
                        + " Expected: " + OFFSETS3[m][0] + "/" + OFFSETS3[m][1]);
            }
        }
    }

    for (int32_t i = 0; i < NUM_TIMEZONES; i++) {
        delete TESTZONES[i];
    }
    delete utc;
    delete cal;
}
Example #21
0
void DateFormatRegressionTest::Test1684(void)
{
  //      July 2001            August 2001           January 2002    
  // Su Mo Tu We Th Fr Sa  Su Mo Tu We Th Fr Sa  Su Mo Tu We Th Fr Sa
  //  1  2  3  4  5  6  7            1  2  3  4         1  2  3  4  5
  //  8  9 10 11 12 13 14   5  6  7  8  9 10 11   6  7  8  9 10 11 12
  // 15 16 17 18 19 20 21  12 13 14 15 16 17 18  13 14 15 16 17 18 19
  // 22 23 24 25 26 27 28  19 20 21 22 23 24 25  20 21 22 23 24 25 26
  // 29 30 31              26 27 28 29 30 31     27 28 29 30 31      
  Test1684Data *tests[] = {
    new Test1684Data(2001, 8,  6,  2001,8,2,UCAL_MONDAY,    "2001 08 02 Mon", NULL),
    new Test1684Data(2001, 8,  7,  2001,8,2,UCAL_TUESDAY,   "2001 08 02 Tue", NULL),
    new Test1684Data(2001, 8,  5,/*12,*/ 2001,8,2,UCAL_SUNDAY,    "2001 08 02 Sun", NULL),
    new Test1684Data(2001, 8,6, /*7,  30,*/ 2001,7,6,UCAL_MONDAY,    "2001 07 06 Mon", "2001 08 02 Mon"),
    new Test1684Data(2001, 8,7, /*7,  31,*/ 2001,7,6,UCAL_TUESDAY,   "2001 07 06 Tue", "2001 08 02 Tue"),
    new Test1684Data(2001, 8,  5,  2001,7,6,UCAL_SUNDAY,    "2001 07 06 Sun", "2001 08 02 Sun"),
    new Test1684Data(2001, 7,  30, 2001,8,1,UCAL_MONDAY,    "2001 08 01 Mon", "2001 07 05 Mon"),
    new Test1684Data(2001, 7,  31, 2001,8,1,UCAL_TUESDAY,   "2001 08 01 Tue", "2001 07 05 Tue"),
    new Test1684Data(2001, 7,29, /*8,  5,*/  2001,8,1,UCAL_SUNDAY,    "2001 08 01 Sun", "2001 07 05 Sun"),
    new Test1684Data(2001, 12, 31, 2001,12,6,UCAL_MONDAY,   "2001 12 06 Mon", NULL),
    new Test1684Data(2002, 1,  1,  2002,1,1,UCAL_TUESDAY,   "2002 01 01 Tue", NULL),
    new Test1684Data(2002, 1,  2,  2002,1,1,UCAL_WEDNESDAY, "2002 01 01 Wed", NULL),
    new Test1684Data(2002, 1,  3,  2002,1,1,UCAL_THURSDAY,  "2002 01 01 Thu", NULL),
    new Test1684Data(2002, 1,  4,  2002,1,1,UCAL_FRIDAY,    "2002 01 01 Fri", NULL),
    new Test1684Data(2002, 1,  5,  2002,1,1,UCAL_SATURDAY,  "2002 01 01 Sat", NULL),
    new Test1684Data(2001,12,30, /*2002, 1,  6,*/  2002,1,1,UCAL_SUNDAY,    "2002 01 01 Sun", "2001 12 06 Sun")
  };

#define kTest1684Count  ((int32_t)(sizeof(tests)/sizeof(tests[0])))

  int32_t pass = 0, error = 0, warning = 0;
  int32_t i;

  UErrorCode status = U_ZERO_ERROR;
  UnicodeString pattern("yyyy MM WW EEE","");
  Calendar *cal = new GregorianCalendar(status);
  SimpleDateFormat *sdf = new SimpleDateFormat(pattern,status);
  if (U_FAILURE(status)) {
    dataerrln("Error constructing SimpleDateFormat");
    for(i=0;i<kTest1684Count;i++) {
        delete tests[i];
    }
    delete cal;
    delete sdf;
    return;
  }
  cal->setFirstDayOfWeek(UCAL_SUNDAY);
  cal->setMinimalDaysInFirstWeek(1);

  sdf->adoptCalendar(cal);

  cal = sdf->getCalendar()->clone(); // sdf may have deleted calendar

  if(!cal || !sdf || U_FAILURE(status)) {
    errln(UnicodeString("Error setting up test: ") + u_errorName(status));
  }

  for (i = 0; i < kTest1684Count; ++i) {
    Test1684Data &test = *(tests[i]);
    logln(UnicodeString("#") + i + UnicodeString("\n-----\nTesting round trip of ") + test.year +
        " " + (test.month + 1) +
        " " + test.date +
          " (written as) " + test.data);
    
    cal->clear();
    cal->set(test.year, test.month, test.date);
    UDate ms = cal->getTime(status);
    
    cal->clear();
    cal->set(UCAL_YEAR, test.womyear);
    cal->set(UCAL_MONTH, test.wommon);
    cal->set(UCAL_WEEK_OF_MONTH, test.wom);
    cal->set(UCAL_DAY_OF_WEEK, test.dow);
    UDate ms2 = cal->getTime(status);
            
    if (ms2 != ms) {
      errln((UnicodeString)"\nError: GregorianUCAL_DOM gave " + ms +
            "\n       GregorianUCAL_WOM gave " + ms2);
      error++;
    } else {
      pass++;
    }
    
    ms2 = sdf->parse(test.data, status);
    if(U_FAILURE(status)) {
      errln("parse exception: " + UnicodeString(u_errorName(status)));
    }
    
    if (ms2!=ms) {
      errln((UnicodeString)"\nError: GregorianCalendar gave      " + ms +
            "\n       SimpleDateFormat.parse gave " + ms2);
      error++;
    } else {
      pass++;
    }

    UnicodeString result;
    sdf->format(ms, result);
    if (result != test.normalized) {
      errln("\nWarning: format of '" + test.data + "' gave" +
            "\n                   '" + result + "'" +
            "\n          expected '" + test.normalized + "'");
      warning++;
    } else {
      pass++;
    }
            
    UDate ms3;
    ms3 = sdf->parse(result, status);
    if(U_FAILURE(status)) {
      errln("parse exception 2: " + (UnicodeString)u_errorName(status));
    }
    
    if (ms3!=ms) {
      error++;
      errln((UnicodeString)"\nError: Re-parse of '" + result + "' gave time of " +
          "\n        " + ms3 +
          "\n    not " + ms);
    } else {
      pass++;
            }
  }

  UnicodeString info 
    = UnicodeString("Passed: ") + pass + ", Warnings: " + warning + ", Errors: " + error;
  if (error > 0) {
    errln(info);
  } else {
    logln(info);
  }

  for(i=0;i<kTest1684Count;i++) {
    delete tests[i];
  }
  delete cal;
  delete sdf;
}
Example #22
0
/**
 * Test the behavior of SimpleTimeZone at the transition into and out of DST.
 * Use a binary search to find boundaries.
 */
void
TimeZoneBoundaryTest::TestBoundaries()
{
    UErrorCode status = U_ZERO_ERROR;
    TimeZone* pst = TimeZone::createTimeZone("PST");
    Calendar* tempcal = Calendar::createInstance(pst, status);
    if(U_SUCCESS(status)){
        verifyMapping(*tempcal, 1997, Calendar::APRIL, 3,  0, 238904.0);
        verifyMapping(*tempcal, 1997, Calendar::APRIL, 4,  0, 238928.0);
        verifyMapping(*tempcal, 1997, Calendar::APRIL, 5,  0, 238952.0);
        verifyMapping(*tempcal, 1997, Calendar::APRIL, 5, 23, 238975.0);
        verifyMapping(*tempcal, 1997, Calendar::APRIL, 6,  0, 238976.0);
        verifyMapping(*tempcal, 1997, Calendar::APRIL, 6,  1, 238977.0);
        verifyMapping(*tempcal, 1997, Calendar::APRIL, 6,  3, 238978.0);
    }else{
        dataerrln("Could not create calendar. Error: %s", u_errorName(status));
    }
    TimeZone* utc = TimeZone::createTimeZone("UTC");
    Calendar* utccal =  Calendar::createInstance(utc, status);
    if(U_SUCCESS(status)){
        verifyMapping(*utccal, 1997, Calendar::APRIL, 6, 0, 238968.0);
    }else{
        dataerrln("Could not create calendar. Error: %s", u_errorName(status));
    }
    TimeZone* save = TimeZone::createDefault();
    TimeZone::setDefault(*pst);
   
    if (tempcal != NULL) { 
        // DST changeover for PST is 4/6/1997 at 2 hours past midnight
        // at 238978.0 epoch hours.
        tempcal->clear();
        tempcal->set(1997, Calendar::APRIL, 6);
        UDate d = tempcal->getTime(status);

        // i is minutes past midnight standard time
        for (int i=-120; i<=180; i+=60)
        {
            UBool inDST = (i >= 120);
            tempcal->setTime(d + i*60*1000, status);
            verifyDST(tempcal->getTime(status),pst, TRUE, inDST, -8*ONE_HOUR,inDST ? -7*ONE_HOUR : -8*ONE_HOUR);
        }
    }
    TimeZone::setDefault(*save);
    delete save;
    delete utccal;
    delete tempcal;

#if 1
    {
        logln("--- Test a ---");
        UDate d = date(97, UCAL_APRIL, 6);
        TimeZone *z = TimeZone::createTimeZone("PST");
        for (int32_t i = 60; i <= 180; i += 15) {
            UBool inDST = (i >= 120);
            UDate e = d + i * 60 * 1000;
            verifyDST(e, z, TRUE, inDST, - 8 * ONE_HOUR, inDST ? - 7 * ONE_HOUR: - 8 * ONE_HOUR);
        }
        delete z;
    }
#endif
#if 1
    {
        logln("--- Test b ---");
        TimeZone *tz;
        TimeZone::setDefault(*(tz = TimeZone::createTimeZone("PST")));
        delete tz;
        logln("========================================");
        findDaylightBoundaryUsingDate(date(97, 0, 1), "PST", PST_1997_BEG);
        logln("========================================");
        findDaylightBoundaryUsingDate(date(97, 6, 1), "PDT", PST_1997_END);
    }
#endif
#if 1
    {
        logln("--- Test c ---");
        logln("========================================");
        TimeZone* z = TimeZone::createTimeZone("Australia/Adelaide");
        findDaylightBoundaryUsingTimeZone(date(97, 0, 1), TRUE, 859653000000.0, z);
        logln("========================================");
        findDaylightBoundaryUsingTimeZone(date(97, 6, 1), FALSE, 877797000000.0, z);
        delete z;
    }
#endif
#if 1
    {
        logln("--- Test d ---");
        logln("========================================");
        findDaylightBoundaryUsingTimeZone(date(97, 0, 1), FALSE, PST_1997_BEG);
        logln("========================================");
        findDaylightBoundaryUsingTimeZone(date(97, 6, 1), TRUE, PST_1997_END);
    }
#endif
#if 0
    {
        logln("--- Test e ---");
        TimeZone *z = TimeZone::createDefault();
        logln(UnicodeString("") + z->getOffset(1, 97, 3, 4, 6, 0) + " " + date(97, 3, 4));
        logln(UnicodeString("") + z->getOffset(1, 97, 3, 5, 7, 0) + " " + date(97, 3, 5));
        logln(UnicodeString("") + z->getOffset(1, 97, 3, 6, 1, 0) + " " + date(97, 3, 6));
        logln(UnicodeString("") + z->getOffset(1, 97, 3, 7, 2, 0) + " " + date(97, 3, 7));
        delete z;
    }
#endif
}
Example #23
0
int main(int argc, char **argv) {

    Calendar *cal;
    DateFormat *fmt;
    DateFormat *defFmt;
    Transliterator *greek_latin;
    Transliterator *rbtUnaccent;
    Transliterator *unaccent;
    UParseError pError;
    UErrorCode status = U_ZERO_ERROR;
    Locale greece("el", "GR");
    UnicodeString str, str2;

    // Create a calendar in the Greek locale
    cal = Calendar::createInstance(greece, status);
    check(status, "Calendar::createInstance");

    // Create a formatter
    fmt = DateFormat::createDateInstance(DateFormat::kFull, greece);
    fmt->setCalendar(*cal);

    // Create a default formatter
    defFmt = DateFormat::createDateInstance(DateFormat::kFull);
    defFmt->setCalendar(*cal);

    // Create a Greek-Latin Transliterator
    greek_latin = Transliterator::createInstance("Greek-Latin", UTRANS_FORWARD, status);
    if (greek_latin == 0) {
        printf("ERROR: Transliterator::createInstance() failed\n");
        exit(1);
    }

    // Create a custom Transliterator
    rbtUnaccent = Transliterator::createFromRules("RBTUnaccent",
                                                  UNACCENT_RULES,
                                                  UTRANS_FORWARD,
                                                  pError,
                                                  status);
    check(status, "Transliterator::createFromRules");

    // Create a custom Transliterator
    unaccent = new UnaccentTransliterator();

    // Loop over various months
    for (int32_t month = Calendar::JANUARY;
         month <= Calendar::DECEMBER;
         ++month) {

        // Set the calendar to a date
        cal->clear();
        cal->set(1999, month, 4);
        
        // Format the date in default locale
        str.remove();
        defFmt->format(cal->getTime(status), str, status);
        check(status, "DateFormat::format");
        printf("Date: ");
        uprintf(escape(str));
        printf("\n");
        
        // Format the date for Greece
        str.remove();
        fmt->format(cal->getTime(status), str, status);
        check(status, "DateFormat::format");
        printf("Greek formatted date: ");
        uprintf(escape(str));
        printf("\n");
        
        // Transliterate result
        greek_latin->transliterate(str);
        printf("Transliterated via Greek-Latin: ");
        uprintf(escape(str));
        printf("\n");
        
        // Transliterate result
        str2 = str;
        rbtUnaccent->transliterate(str);
        printf("Transliterated via RBT unaccent: ");
        uprintf(escape(str));
        printf("\n");

        unaccent->transliterate(str2);
        printf("Transliterated via normalizer unaccent: ");
        uprintf(escape(str2));
        printf("\n\n");
    }

    // Clean up
    delete fmt;
    delete cal;
    delete greek_latin;
    delete unaccent;
    delete rbtUnaccent;

    printf("Exiting successfully\n");
    return 0;
}
Example #24
0
void CalendarTest::calendarTest () {

//	try {
		 
	XMLBEANSXX_DEBUG(logger, "++++++++++ Calendar Test ++++++++++");
	
	Calendar c;
	c.setYear(1978).setMonth("   10 		");
	XMLBEANSXX_DEBUG(logger, "c.getDst: " + TextUtils::intToString(c.getDst()));

	XMLBEANSXX_DEBUG(logger, "c.setYear(1978)");
	XMLBEANSXX_DEBUG(logger, "c.hasYear(): " + TextUtils::boolToString(c.hasYear()) + " ,c.getYear(): " + TextUtils::intToString(c.getYear()));
	CPPUNIT_ASSERT(c.hasYear() == true);
	CPPUNIT_ASSERT(c.getYear() == 1978);
	XMLBEANSXX_DEBUG(logger, "c.setMonth(\"10\")");
	XMLBEANSXX_DEBUG(logger, "c.hasMonth(): " + TextUtils::boolToString(c.hasMonth()) + " ,c.getMonth(): " + TextUtils::intToString(c.getMonth()));
	CPPUNIT_ASSERT(c.hasMonth() == true);
	CPPUNIT_ASSERT(c.getMonth() == 10);
	XMLBEANSXX_DEBUG(logger, "c.hasDay(): " + TextUtils::boolToString(c.hasDay()) + " ,c.getDay(): " + TextUtils::intToString(c.getDay()));
	CPPUNIT_ASSERT(c.hasDay() == false);

	c.setDay(31);

	XMLBEANSXX_DEBUG(logger, "c.setDay(31)");
	XMLBEANSXX_DEBUG(logger, "c.hasDay(): " + TextUtils::boolToString(c.hasDay()) + " ,c.getDay(): " + TextUtils::intToString(c.getDay()));
	CPPUNIT_ASSERT(c.hasDay() == true);
	CPPUNIT_ASSERT(c.getDay() == 31);
	
	CPPUNIT_ASSERT(c.hasFullDateInfo() == true);

	c.setHour(15);
	c.setMinutes("\t  22 ");
	c.setSeconds(47);

	XMLBEANSXX_DEBUG(logger, "c.setHour(15)");
	XMLBEANSXX_DEBUG(logger, "c.hasHour(): " + TextUtils::boolToString(c.hasHour()) + " ,c.getHour(): " + TextUtils::intToString(c.getHour()));

	CPPUNIT_ASSERT(c.hasHour() == true);
	CPPUNIT_ASSERT(c.getHour() == 15);
	CPPUNIT_ASSERT(c.hasMinutes() == true);
	CPPUNIT_ASSERT(c.getMinutes() == 22);
	CPPUNIT_ASSERT(c.hasSeconds() == true);
	CPPUNIT_ASSERT(c.getSeconds() == 47);

	CPPUNIT_ASSERT(c.hasFullTimeInfo() == true);
	CPPUNIT_ASSERT(c.hasFracSec() == false);

	XMLBEANSXX_DEBUG(logger, "c.getBDate(): " + boost::gregorian::to_simple_string(c.getDate()));
	XMLBEANSXX_DEBUG(logger, "c.getBPtime(): " + boost::posix_time::to_simple_string(c.getTime()));

	c.setFracSec(123);
	CPPUNIT_ASSERT(c.hasFracSec() == true);
	CPPUNIT_ASSERT(c.getFracSec() == 123);
	XMLBEANSXX_DEBUG(logger, "c.getBPtime(): " + boost::posix_time::to_simple_string(c.getTime()));

	XMLBEANSXX_DEBUG(logger, "+++++++ Time Zone Test +++++++");

	XMLBEANSXX_DEBUG(logger, "c.hasTimeZone: " + TextUtils::boolToString(c.hasTimeZone()));
	XMLBEANSXX_DEBUG(logger, "c.isSetDt: " + TextUtils::boolToString(c.isSetDst()));
	XMLBEANSXX_DEBUG(logger, "c.getDst: " + TextUtils::intToString(c.getDst()));
	XMLBEANSXX_DEBUG(logger, "c.getUTCTime: " + boost::posix_time::to_simple_string(c.getUTCTime()));
	XMLBEANSXX_DEBUG(logger, "c.getLocalTime: " + boost::posix_time::to_simple_string(c.getLocalTime()));

	CPPUNIT_ASSERT(c.hasTimeZone() == false);
	CPPUNIT_ASSERT(c.isSetDst() == false);
	CPPUNIT_ASSERT(boost::posix_time::to_simple_string(c.getUTCTime()) == "not-a-date-time");
	CPPUNIT_ASSERT(boost::posix_time::to_simple_string(c.getLocalTime()) == "not-a-date-time");
	
	c.setGmtOff(1, 0).dstUnknown();
	
	XMLBEANSXX_DEBUG(logger, "c.setGmtOff(1,0).dstUnknown()");
	XMLBEANSXX_DEBUG(logger, "c.hasTimeZone: " + TextUtils::boolToString(c.hasTimeZone()));
	XMLBEANSXX_DEBUG(logger, "c.isSetDst: " + TextUtils::boolToString(c.isSetDst()));
	XMLBEANSXX_DEBUG(logger, "c.getUTCTime: " + boost::posix_time::to_simple_string(c.getUTCTime()));
	XMLBEANSXX_DEBUG(logger, "c.getLocalTime: " + boost::posix_time::to_simple_string(c.getLocalTime()));

	c.dstOn();

	XMLBEANSXX_DEBUG(logger, "c.dstOn()");
	XMLBEANSXX_DEBUG(logger, "c.hasTimeZone: " + TextUtils::boolToString(c.hasTimeZone()));
	XMLBEANSXX_DEBUG(logger, "c.isSetDst: " + TextUtils::boolToString(c.isSetDst()));
	XMLBEANSXX_DEBUG(logger, "c.getUTCTime: " + boost::posix_time::to_simple_string(c.getUTCTime()));
	XMLBEANSXX_DEBUG(logger, "c.getLocalTime: " + boost::posix_time::to_simple_string(c.getLocalTime()));
	XMLBEANSXX_DEBUG(logger, "c.toXsdDateTime: " + c.toXsdDateTime());
	XMLBEANSXX_DEBUG(logger, "c.toXsdDate: " + c.toXsdDate());
	XMLBEANSXX_DEBUG(logger, "c.toXsdTime: " + c.toXsdTime());
	
	CPPUNIT_ASSERT(c.hasTimeZone() == true);
	CPPUNIT_ASSERT(c.isSetDst() == true);
	CPPUNIT_ASSERT(boost::posix_time::to_simple_string(c.getUTCTime()) == "1978-Oct-31 13:22:47.123000");
	CPPUNIT_ASSERT(boost::posix_time::to_simple_string(c.getLocalTime()) == "1978-Oct-31 15:22:47.123000");
	CPPUNIT_ASSERT(c.toXsdDate() == "1978-10-31+02:00");
	CPPUNIT_ASSERT(c.toXsdDateTime() == "1978-10-31T15:22:47.123+02:00");
	CPPUNIT_ASSERT(c.toXsdTime() == "15:22:47.123+02:00");

	Calendar d("  \t\t\t\t\n\n\n\n\n  2008-12-12T02:22:22.123-12:33    \t  \n\n");
	
	XMLBEANSXX_DEBUG(logger, "Calendar d(\"2008-12-12T02:22:22.123-12:33\");");
	XMLBEANSXX_DEBUG(logger, "d.hasTimeZone: " + TextUtils::boolToString(d.hasTimeZone()));
	XMLBEANSXX_DEBUG(logger, "d.isDstOn: " + TextUtils::boolToString(d.isDstOn()));
	XMLBEANSXX_DEBUG(logger, "d.isSetDst: " + TextUtils::boolToString(d.isSetDst()));
	XMLBEANSXX_DEBUG(logger, "d.getBPtime: " + boost::posix_time::to_simple_string(d.getTime()));
	XMLBEANSXX_DEBUG(logger, "d.getUTCTime: " + boost::posix_time::to_simple_string(d.getUTCTime()));
	XMLBEANSXX_DEBUG(logger, "d.getLocalTime: " + boost::posix_time::to_simple_string(d.getLocalTime()));
	XMLBEANSXX_DEBUG(logger, "d.toXsdDateTime: " + d.toXsdDateTime());
	XMLBEANSXX_DEBUG(logger, "d.toXsdDate: " + d.toXsdDate());
	XMLBEANSXX_DEBUG(logger, "d.toXsdTime: " + d.toXsdTime());

	CPPUNIT_ASSERT(d.hasTimeZone() == true);
	CPPUNIT_ASSERT(d.isDstOn() == false);
	CPPUNIT_ASSERT(d.isSetDst() == true);
	CPPUNIT_ASSERT(boost::posix_time::to_simple_string(d.getTime()) == "2008-Dec-12 02:22:22.123000");
	CPPUNIT_ASSERT(boost::posix_time::to_simple_string(d.getUTCTime()) == "2008-Dec-12 14:55:22.123000");
	CPPUNIT_ASSERT(boost::posix_time::to_simple_string(d.getLocalTime()) == "2008-Dec-12 02:22:22.123000");
	CPPUNIT_ASSERT(d.toXsdDateTime() == "2008-12-12T02:22:22.123-12:33");
	CPPUNIT_ASSERT(d.toXsdDate() == "2008-12-12-12:33");
	CPPUNIT_ASSERT(d.toXsdTime() == "02:22:22.123-12:33");

	Calendar e(" 2008-12-12T12:12:12.121Z  ");
	
	XMLBEANSXX_DEBUG(logger, "e.hasTimeZone: " + TextUtils::boolToString(e.hasTimeZone()));
	XMLBEANSXX_DEBUG(logger, "e.hasFullTimeInfo: " + TextUtils::boolToString(e.hasFullTimeInfo()));
	XMLBEANSXX_DEBUG(logger, "e.isDstOn: " + TextUtils::boolToString(e.isDstOn()));
	XMLBEANSXX_DEBUG(logger, "e.isSetDst: " + TextUtils::boolToString(e.isSetDst()));
	XMLBEANSXX_DEBUG(logger, "e.getBDate: " + boost::gregorian::to_simple_string(e.getDate()));
	XMLBEANSXX_DEBUG(logger, "-->e.getBDate: " + e.dateToString());
	XMLBEANSXX_DEBUG(logger, "e.getBPtime: " + boost::posix_time::to_simple_string(e.getTime()));
	XMLBEANSXX_DEBUG(logger, "-->e.getBPtime: " + e.timeToString());
	XMLBEANSXX_DEBUG(logger, "e.getUTCTime: " + boost::posix_time::to_simple_string(e.getUTCTime()));
	XMLBEANSXX_DEBUG(logger, "-->e.getUTCTime: " + e.utcTimeToString());
	XMLBEANSXX_DEBUG(logger, "e.getLocalTime: " + boost::posix_time::to_simple_string(e.getLocalTime()));
	XMLBEANSXX_DEBUG(logger, "-->e.getLocalTime: " + e.localTimeToString());
	XMLBEANSXX_DEBUG(logger, "e.toXsdDateTime: " + e.toXsdDateTime());
	XMLBEANSXX_DEBUG(logger, "e.toXsdDate: " + e.toXsdDate());
	XMLBEANSXX_DEBUG(logger, "e.toXsdTime: " + e.toXsdTime());

	CPPUNIT_ASSERT(e.hasTimeZone() == true);
	CPPUNIT_ASSERT(e.hasFullTimeInfo() == true);
	CPPUNIT_ASSERT(e.isDstOn() == false);
	CPPUNIT_ASSERT(e.isSetDst() == true);
	CPPUNIT_ASSERT(boost::gregorian::to_simple_string(e.getDate()) == "2008-Dec-12");
	CPPUNIT_ASSERT(e.dateToString() == "2008-12-12");
	CPPUNIT_ASSERT(boost::posix_time::to_simple_string(e.getTime()) == "2008-Dec-12 12:12:12.121000");
	CPPUNIT_ASSERT(e.timeToString() == "2008-12-12T12:12:12.121000");
	CPPUNIT_ASSERT(boost::posix_time::to_simple_string(e.getUTCTime()) == "2008-Dec-12 12:12:12.121000");
	CPPUNIT_ASSERT(e.utcTimeToString() == "2008-12-12T12:12:12.121000");
	CPPUNIT_ASSERT(boost::posix_time::to_simple_string(e.getLocalTime()) == "2008-Dec-12 12:12:12.121000");
	CPPUNIT_ASSERT(e.localTimeToString() == "2008-12-12T12:12:12.121000");
	CPPUNIT_ASSERT(e.toXsdDateTime() == "2008-12-12T12:12:12.121Z");
	CPPUNIT_ASSERT(e.toXsdDate() == "2008-12-12Z");
	CPPUNIT_ASSERT(e.toXsdTime() == "12:12:12.121Z");

	e.setDate("   2008-12-12+12:12   ").setYearMonth("   2008-12-12:22   ").setgYear("   2008-12:22   ");
	e.setMonthDay("   --12-22Z   ").setgDay(" 			  ---22-12:31   ").setgMonth("   --12+12:12   ");
	
	XMLBEANSXX_DEBUG(logger, "e.hasTimeZone: " + TextUtils::boolToString(e.hasTimeZone()));
	XMLBEANSXX_DEBUG(logger, "e.isDstOn: " + TextUtils::boolToString(e.isDstOn()));
	XMLBEANSXX_DEBUG(logger, "e.isSetDst: " + TextUtils::boolToString(e.isSetDst()));
	XMLBEANSXX_DEBUG(logger, "e.getBDate: " + boost::gregorian::to_simple_string(e.getDate()));
	XMLBEANSXX_DEBUG(logger, "-->e.getBDate: " + e.dateToString());
	XMLBEANSXX_DEBUG(logger, "e.getBPtime: " + boost::posix_time::to_simple_string(e.getTime()));
	XMLBEANSXX_DEBUG(logger, "-->e.getBPtime: " + e.timeToString());
	XMLBEANSXX_DEBUG(logger, "e.getUTCTime: " + boost::posix_time::to_simple_string(e.getUTCTime()));
	XMLBEANSXX_DEBUG(logger, "-->e.getUTCTime: " + e.utcTimeToString());
	XMLBEANSXX_DEBUG(logger, "e.getLocalTime: " + boost::posix_time::to_simple_string(e.getLocalTime()));
	XMLBEANSXX_DEBUG(logger, "-->e.getLocalTime: " + e.localTimeToString());
	XMLBEANSXX_DEBUG(logger, "e.toXsdDateTime: " + e.toXsdDateTime());
	XMLBEANSXX_DEBUG(logger, "e.toXsdDate: " + e.toXsdDate());
	XMLBEANSXX_DEBUG(logger, "e.toXsdTime: " + e.toXsdTime());
	XMLBEANSXX_DEBUG(logger, "e.toXsdYearMonth: " + e.toXsdYearMonth());
	XMLBEANSXX_DEBUG(logger, "e.toXsdYear: " + e.toXsdYear());
	XMLBEANSXX_DEBUG(logger, "e.toXsdMonthDay: " + e.toXsdMonthDay());
	XMLBEANSXX_DEBUG(logger, "e.toXsdMonth: " + e.toXsdMonth());
	XMLBEANSXX_DEBUG(logger, "e.toXsdDay: " + e.toXsdDay());
	XMLBEANSXX_DEBUG(logger, "e.toString: " + e.toString());
	
	CPPUNIT_ASSERT(e.hasTimeZone() == true);
	CPPUNIT_ASSERT(e.hasFullTimeInfo() == true);
	CPPUNIT_ASSERT(e.isDstOn() == false);
	CPPUNIT_ASSERT(e.isSetDst() == true);
	CPPUNIT_ASSERT(boost::gregorian::to_simple_string(e.getDate()) == "2008-Dec-22");
	CPPUNIT_ASSERT(e.dateToString() == "2008-12-22");
	CPPUNIT_ASSERT(boost::posix_time::to_simple_string(e.getTime()) == "2008-Dec-22 12:12:12.121000");
	CPPUNIT_ASSERT(e.timeToString() == "2008-12-22T12:12:12.121000");
	CPPUNIT_ASSERT(boost::posix_time::to_simple_string(e.getUTCTime()) == "2008-Dec-22 00:00:12.121000");
	CPPUNIT_ASSERT(e.utcTimeToString() == "2008-12-22T00:00:12.121000");
	CPPUNIT_ASSERT(boost::posix_time::to_simple_string(e.getLocalTime()) == "2008-Dec-22 12:12:12.121000");
	CPPUNIT_ASSERT(e.localTimeToString() == "2008-12-22T12:12:12.121000");
	CPPUNIT_ASSERT(e.toXsdDateTime() == "2008-12-22T12:12:12.121+12:12");
	CPPUNIT_ASSERT(e.toXsdDate() == "2008-12-22+12:12");
	CPPUNIT_ASSERT(e.toXsdTime() == "12:12:12.121+12:12");
	CPPUNIT_ASSERT(e.toXsdYearMonth() == "2008-12+12:12");
	CPPUNIT_ASSERT(e.toXsdYear() == "2008+12:12");
	CPPUNIT_ASSERT(e.toXsdMonthDay() == "--12-22+12:12");
	CPPUNIT_ASSERT(e.toXsdMonth() == "--12+12:12");
	CPPUNIT_ASSERT(e.toXsdDay() == "---22+12:12");

	XMLBEANSXX_DEBUG(logger, "+++++++ Guessing Time Zone +++++++");

	Calendar a(" 2008-05-05T15:11:22 \n\n\n");
	Calendar b(" 2008-01-01T15:11:22 \n\n\n");
	XMLBEANSXX_DEBUG(logger, "a -> " + a.toXsdDateTime());
	XMLBEANSXX_DEBUG(logger, "b -> " + b.toXsdDateTime());

	CPPUNIT_ASSERT(a.hasTimeZone() == false);
	CPPUNIT_ASSERT(a.isSetDst() == false);
	CPPUNIT_ASSERT(b.hasTimeZone() == false);
	CPPUNIT_ASSERT(b.isSetDst() == false);

	a.timeZoneGuess();
	XMLBEANSXX_DEBUG(logger, "a -> " + a.toXsdDateTime());
	b.timeZoneGuess();
	XMLBEANSXX_DEBUG(logger, "b -> " + b.toXsdDateTime());
	
	CPPUNIT_ASSERT(a.hasTimeZone() == true);
	CPPUNIT_ASSERT(a.isSetDst() == true);
	CPPUNIT_ASSERT(b.hasTimeZone() == true);
	CPPUNIT_ASSERT(b.isSetDst() == true);
	
	CPPUNIT_ASSERT(a.localTimeToString() == "2008-05-05T15:11:22");
	CPPUNIT_ASSERT(b.localTimeToString() == "2008-01-01T15:11:22");

	XMLBEANSXX_INFO(logger, "Time Zone Specific Test! Start"); 
	//Working in CET/CEST time zone
	CPPUNIT_ASSERT(a.toXsdDateTime() == "2008-05-05T15:11:22+02:00");
	CPPUNIT_ASSERT(a.utcTimeToString() == "2008-05-05T13:11:22");
	CPPUNIT_ASSERT(b.toXsdDateTime() == "2008-01-01T15:11:22+01:00");
	CPPUNIT_ASSERT(b.utcTimeToString() == "2008-01-01T14:11:22");
	XMLBEANSXX_INFO(logger, "Time Zone Specific Test! End");
	
	XMLBEANSXX_DEBUG(logger, "+++++++ Duration Test +++++++");

	Duration q1("P1Y1M1DT1H1M1.1S");
	Duration q2("P2Y2M2DT2H2M2.123S");

	XMLBEANSXX_DEBUG(logger, "q1-->" + q1.toString());
	XMLBEANSXX_DEBUG(logger, "q2-->" + q2.toString());
	
	CPPUNIT_ASSERT(q1.toString() == "P1Y1M1DT1H1M1.001S");
	CPPUNIT_ASSERT(q2.toString() == "P2Y2M2DT2H2M2.123S");

	Duration q3("-P1YT3M");
	
	XMLBEANSXX_DEBUG(logger, "q3-->" + q3.toString());
	CPPUNIT_ASSERT(q3.toString() == "-P1YT3M");

	Duration q4;
	
	XMLBEANSXX_DEBUG(logger, "q4-->" + q4.toString());
	CPPUNIT_ASSERT(q4.toString() == "P");

	Calendar test(" 2000-01-12T12:13:14Z");
	XMLBEANSXX_DEBUG(logger, "test ->" + test.toXsdDateTime());
	Duration dur(" 	P1Y3M5DT7H10M3.3S ");
	XMLBEANSXX_DEBUG(logger, "dur  ->" + dur.toString());
	Calendar sol = test + dur;

	CPPUNIT_ASSERT(sol.toXsdDateTime() == "2001-04-17T19:23:17.003Z");

	XMLBEANSXX_DEBUG(logger, "sol = test + dur -> " + sol.toXsdDateTime());

	Calendar test2;
	test2.setYear(2000).setMonth(1).setGmtOff(1,43).dstOff();
	XMLBEANSXX_DEBUG(logger, "test2 ->" + test2.toXsdYearMonth());
	Duration dur2(" 	-P3M ");
	XMLBEANSXX_DEBUG(logger, "dur  ->" + dur2.toString());
	Calendar sol2 = test2 + dur2;

	XMLBEANSXX_DEBUG(logger, "sol2 = test2 + dur2 -> " + sol2.toXsdYearMonth());

	CPPUNIT_ASSERT(sol2.getYear() == 1999);
	CPPUNIT_ASSERT(sol2.getMonth() == 10);
	CPPUNIT_ASSERT(sol2.hasDay() == false);
	CPPUNIT_ASSERT(sol2.toXsdYearMonth() == "1999-10+01:43");

	Calendar test3;
	test3.setDate(" 1999-01-12");
	Duration dur3(" PT33H");

	XMLBEANSXX_DEBUG(logger, "test3 ->" + test3.toXsdDate());
	XMLBEANSXX_DEBUG(logger, "dur  ->" + dur3.toString());
	Calendar sol3 = test3 + dur3;

	XMLBEANSXX_DEBUG(logger, "sol3 = test3 + dur3 -> " + sol3.toXsdDate());
	CPPUNIT_ASSERT(sol3.toXsdDate() == "1999-01-13");
	
	Calendar test4;
	test4.setDate(" 1978-03-31");
	Duration dur4(" P1M");

	XMLBEANSXX_DEBUG(logger, "test4 ->" + test4.toXsdDate());
	XMLBEANSXX_DEBUG(logger, "dur  ->" + dur4.toString());
	Calendar sol4 = test4 +dur4;

	XMLBEANSXX_DEBUG(logger, "sol4 = test4 + dur4 -> " + sol4.toXsdDate());
	CPPUNIT_ASSERT(sol4.toXsdDate() == "1978-04-30");
	XMLBEANSXX_DEBUG(logger, "test4 ->" + test4.toXsdDate());

	Calendar cl1 = test4 + dur4;
	Calendar cl2 = test4 - dur4;
	XMLBEANSXX_DEBUG(logger, test4.toXsdDate() + " + " + dur4.toString() + " = " + cl1.toXsdDate());
	XMLBEANSXX_DEBUG(logger, test4.toXsdDate() + " - " + dur4.toString() + " = " + cl2.toXsdDate());

	CPPUNIT_ASSERT(cl2.toXsdDate() == "1978-02-28");

	//CPPUNIT_ASSERT (false);
	/*
	} catch (BeansException& e) {
		//std::cout << e.what();
	}*/
        
}
  /**
    * getDisplayName doesn't work with unusual savings/offsets.
    */
void TimeZoneRegressionTest::Test4176686() {
    // Construct a zone that does not observe DST but
    // that does have a DST savings (which should be ignored).
    UErrorCode status = U_ZERO_ERROR;
    int32_t offset = 90 * 60000; // 1:30
    SimpleTimeZone* z1 = new SimpleTimeZone(offset, "_std_zone_");
    z1->setDSTSavings(45 * 60000, status); // 0:45

    // Construct a zone that observes DST for the first 6 months.
    SimpleTimeZone* z2 = new SimpleTimeZone(offset, "_dst_zone_");
    z2->setDSTSavings(45 * 60000, status); // 0:45
    z2->setStartRule(UCAL_JANUARY, 1, 0, status);
    z2->setEndRule(UCAL_JULY, 1, 0, status);

    // Also check DateFormat
    DateFormat* fmt1 = new SimpleDateFormat(UnicodeString("z"), status);
    if (U_FAILURE(status)) {
        dataerrln("Failure trying to construct: %s", u_errorName(status));
        return;
    }
    fmt1->setTimeZone(*z1); // Format uses standard zone
    DateFormat* fmt2 = new SimpleDateFormat(UnicodeString("z"), status);
    if(!assertSuccess("trying to construct", status))return;
    fmt2->setTimeZone(*z2); // Format uses DST zone
    Calendar* tempcal = Calendar::createInstance(status);
    tempcal->clear();
    tempcal->set(1970, UCAL_FEBRUARY, 1);
    UDate dst = tempcal->getTime(status); // Time in DST
    tempcal->set(1970, UCAL_AUGUST, 1);
    UDate std = tempcal->getTime(status); // Time in standard

    // Description, Result, Expected Result
    UnicodeString a,b,c,d,e,f,g,h,i,j,k,l;
    UnicodeString DATA[] = {
        "z1->getDisplayName(false, SHORT)/std zone",
        z1->getDisplayName(FALSE, TimeZone::SHORT, a), "GMT+01:30",
        "z1->getDisplayName(false, LONG)/std zone",
        z1->getDisplayName(FALSE, TimeZone::LONG, b), "GMT+01:30",
        "z1->getDisplayName(true, SHORT)/std zone",
        z1->getDisplayName(TRUE, TimeZone::SHORT, c), "GMT+01:30",
        "z1->getDisplayName(true, LONG)/std zone",
        z1->getDisplayName(TRUE, TimeZone::LONG, d ), "GMT+01:30",
        "z2->getDisplayName(false, SHORT)/dst zone",
        z2->getDisplayName(FALSE, TimeZone::SHORT, e), "GMT+01:30",
        "z2->getDisplayName(false, LONG)/dst zone",
        z2->getDisplayName(FALSE, TimeZone::LONG, f ), "GMT+01:30",
        "z2->getDisplayName(true, SHORT)/dst zone",
        z2->getDisplayName(TRUE, TimeZone::SHORT, g), "GMT+02:15",
        "z2->getDisplayName(true, LONG)/dst zone",
        z2->getDisplayName(TRUE, TimeZone::LONG, h ), "GMT+02:15",
        "DateFormat.format(std)/std zone", fmt1->format(std, i), "GMT+01:30",
        "DateFormat.format(dst)/std zone", fmt1->format(dst, j), "GMT+01:30",
        "DateFormat.format(std)/dst zone", fmt2->format(std, k), "GMT+01:30",
        "DateFormat.format(dst)/dst zone", fmt2->format(dst, l), "GMT+02:15",
    };

    for (int32_t idx=0; idx<(int32_t)ARRAY_LENGTH(DATA); idx+=3) {
        if (DATA[idx+1]!=(DATA[idx+2])) {
            errln("FAIL: " + DATA[idx] + " -> " + DATA[idx+1] + ", exp " + DATA[idx+2]);
        }
    }
    delete z1;
    delete z2;
    delete fmt1;
    delete fmt2;
    delete tempcal;
}
/**
 * Verify the Persian Calendar.
 */
void IntlCalendarTest::TestPersian() {
    UDate timeA = Calendar::getNow();
    
    Calendar *cal;
    UErrorCode status = U_ZERO_ERROR;
    cal = Calendar::createInstance("fa_IR@calendar=persian", status);
    CHECK(status, UnicodeString("Creating fa_IR@calendar=persian calendar"));
    // Sanity check the calendar 
    UDate timeB = Calendar::getNow();
    UDate timeCal = cal->getTime(status);

    if(!(timeA <= timeCal) || !(timeCal <= timeB)) {
      errln((UnicodeString)"Error: Calendar time " + timeCal +
            " is not within sampled times [" + timeA + " to " + timeB + "]!");
    }
    // end sanity check

    // Test various dates to be sure of validity
    int32_t data[] = { 
        1925, 4, 24, 1304, 2, 4,
        2011, 1, 11, 1389, 10, 21,
        1986, 2, 25, 1364, 12, 6, 
        1934, 3, 14, 1312, 12, 23,

        2090, 3, 19, 1468, 12, 29,
        2007, 2, 22, 1385, 12, 3,
        1969, 12, 31, 1348, 10, 10,
        1945, 11, 12, 1324, 8, 21,
        1925, 3, 31, 1304, 1, 11,

        1996, 3, 19, 1374, 12, 29,
        1996, 3, 20, 1375, 1, 1,
        1997, 3, 20, 1375, 12, 30,
        1997, 3, 21, 1376, 1, 1,

        2008, 3, 19, 1386, 12, 29,
        2008, 3, 20, 1387, 1, 1,
        2004, 3, 19, 1382, 12, 29,
        2004, 3, 20, 1383, 1, 1,

        2006, 3, 20, 1384, 12, 29,
        2006, 3, 21, 1385, 1, 1,

        2005, 4, 20, 1384, 1, 31,
        2005, 4, 21, 1384, 2, 1,
        2005, 5, 21, 1384, 2, 31,
        2005, 5, 22, 1384, 3, 1,
        2005, 6, 21, 1384, 3, 31,
        2005, 6, 22, 1384, 4, 1,
        2005, 7, 22, 1384, 4, 31,
        2005, 7, 23, 1384, 5, 1,
        2005, 8, 22, 1384, 5, 31,
        2005, 8, 23, 1384, 6, 1,
        2005, 9, 22, 1384, 6, 31,
        2005, 9, 23, 1384, 7, 1,
        2005, 10, 22, 1384, 7, 30,
        2005, 10, 23, 1384, 8, 1,
        2005, 11, 21, 1384, 8, 30,
        2005, 11, 22, 1384, 9, 1,
        2005, 12, 21, 1384, 9, 30,
        2005, 12, 22, 1384, 10, 1,
        2006, 1, 20, 1384, 10, 30,
        2006, 1, 21, 1384, 11, 1,
        2006, 2, 19, 1384, 11, 30,
        2006, 2, 20, 1384, 12, 1,
        2006, 3, 20, 1384, 12, 29,
        2006, 3, 21, 1385, 1, 1,

        // The 2820-year cycle arithmetical algorithm would fail this one.
        2025, 3, 21, 1404, 1, 1,
        
        -1,-1,-1,-1,-1,-1,-1,-1,-1,-1
    };

    Calendar *grego = Calendar::createInstance("fa_IR@calendar=gregorian", status);
    for (int32_t i=0; data[i]!=-1; ) {
        int32_t gregYear = data[i++];
        int32_t gregMonth = data[i++]-1;
        int32_t gregDay = data[i++];
        int32_t persYear = data[i++];
        int32_t persMonth = data[i++]-1;
        int32_t persDay = data[i++];
        
        // Test conversion from Persian dates
        grego->clear();
        grego->set(gregYear, gregMonth, gregDay);

        cal->clear();
        cal->set(persYear, persMonth, persDay);

        UDate persTime = cal->getTime(status);
        UDate gregTime = grego->getTime(status);

        if (persTime != gregTime) {
          errln(UnicodeString("Expected ") + gregTime + " but got " + persTime);
        }

        // Test conversion to Persian dates
        cal->clear();
        cal->setTime(gregTime, status);

        int32_t computedYear = cal->get(UCAL_YEAR, status);
        int32_t computedMonth = cal->get(UCAL_MONTH, status);
        int32_t computedDay = cal->get(UCAL_DATE, status);

        if ((persYear != computedYear) ||
            (persMonth != computedMonth) ||
            (persDay != computedDay)) {
          errln(UnicodeString("Expected ") + persYear + "/" + (persMonth+1) + "/" + persDay +
                " but got " +  computedYear + "/" + (computedMonth+1) + "/" + computedDay);
        }

    }

    delete cal;
    delete grego;
}
Example #27
0
UBool
Calendar::equals(const Calendar& when, UErrorCode& status) const
{
    return (this == &when ||
            getTime(status) == when.getTime(status));
}
Example #28
0
/**
* Return the maximum value that this field could have, given the current date.
* For example, with the date "Feb 3, 1997" and the DAY_OF_MONTH field, the actual
* maximum would be 28; for "Feb 3, 1996" it s 29.  Similarly for a Hebrew calendar,
* for some years the actual maximum for MONTH is 12, and for others 13.
* @stable ICU 2.0
*/
int32_t GregorianCalendar::getActualMaximum(UCalendarDateFields field, UErrorCode& status) const
{
    /* It is a known limitation that the code here (and in getActualMinimum)
    * won't behave properly at the extreme limits of GregorianCalendar's
    * representable range (except for the code that handles the YEAR
    * field).  That's because the ends of the representable range are at
    * odd spots in the year.  For calendars with the default Gregorian
    * cutover, these limits are Sun Dec 02 16:47:04 GMT 292269055 BC to Sun
    * Aug 17 07:12:55 GMT 292278994 AD, somewhat different for non-GMT
    * zones.  As a result, if the calendar is set to Aug 1 292278994 AD,
    * the actual maximum of DAY_OF_MONTH is 17, not 30.  If the date is Mar
    * 31 in that year, the actual maximum month might be Jul, whereas is
    * the date is Mar 15, the actual maximum might be Aug -- depending on
    * the precise semantics that are desired.  Similar considerations
    * affect all fields.  Nonetheless, this effect is sufficiently arcane
    * that we permit it, rather than complicating the code to handle such
    * intricacies. - liu 8/20/98

    * UPDATE: No longer true, since we have pulled in the limit values on
    * the year. - Liu 11/6/00 */

    switch (field) {

    case UCAL_YEAR:
        /* The year computation is no different, in principle, from the
        * others, however, the range of possible maxima is large.  In
        * addition, the way we know we've exceeded the range is different.
        * For these reasons, we use the special case code below to handle
        * this field.
        *
        * The actual maxima for YEAR depend on the type of calendar:
        *
        *     Gregorian = May 17, 292275056 BC - Aug 17, 292278994 AD
        *     Julian    = Dec  2, 292269055 BC - Jan  3, 292272993 AD
        *     Hybrid    = Dec  2, 292269055 BC - Aug 17, 292278994 AD
        *
        * We know we've exceeded the maximum when either the month, date,
        * time, or era changes in response to setting the year.  We don't
        * check for month, date, and time here because the year and era are
        * sufficient to detect an invalid year setting.  NOTE: If code is
        * added to check the month and date in the future for some reason,
        * Feb 29 must be allowed to shift to Mar 1 when setting the year.
        */
        {
            if(U_FAILURE(status)) return 0;
            Calendar *cal = clone();
            if(!cal) {
                status = U_MEMORY_ALLOCATION_ERROR;
                return 0;
            }

            cal->setLenient(TRUE);

            int32_t era = cal->get(UCAL_ERA, status);
            UDate d = cal->getTime(status);

            /* Perform a binary search, with the invariant that lowGood is a
            * valid year, and highBad is an out of range year.
            */
            int32_t lowGood = kGregorianCalendarLimits[UCAL_YEAR][1];
            int32_t highBad = kGregorianCalendarLimits[UCAL_YEAR][2]+1;
            while ((lowGood + 1) < highBad) {
                int32_t y = (lowGood + highBad) / 2;
                cal->set(UCAL_YEAR, y);
                if (cal->get(UCAL_YEAR, status) == y && cal->get(UCAL_ERA, status) == era) {
                    lowGood = y;
                } else {
                    highBad = y;
                    cal->setTime(d, status); // Restore original fields
                }
            }

            delete cal;
            return lowGood;
        }

    default:
        return Calendar::getActualMaximum(field,status);
    }
}
Example #29
0
static void dtitvfmtPreDefined() {
	  
	u_printf("===============================================================================\n");
	u_printf(" dtitvfmtPreDefined()\n");
    u_printf("\n");
    u_printf(" Use DateIntervalFormat to get date interval format for pre-defined skeletons:\n");
    u_printf(" yMMMd, MMMMd, jm per locale\n");
    u_printf("===============================================================================\n");
	
	//! [dtitvfmtPreDefined] 
	UFILE *out = u_finit(stdout, NULL, "UTF-8");
	UErrorCode status =U_ZERO_ERROR;
	// create 3 Date Intervals
	UnicodeString data[] = {
		UnicodeString("2007-10-10 10:10:10"),
		UnicodeString("2008-10-10 10:10:10"),
		UnicodeString("2008-11-10 10:10:10"),
		UnicodeString("2008-11-10 15:10:10")
		};
	Calendar *cal = Calendar::createInstance(status);
	cal->set(2007,10,10,10,10,10);
	UDate date1 = cal->getTime(status);
	cal->set(2008,10,10,10,10,10);
	UDate date2 = cal->getTime(status);
	cal->set(2008,11,10,10,10,10);
	UDate date3 = cal->getTime(status);
	cal->set(2008,11,10,15,10,10);
	UDate date4 = cal->getTime(status);
    DateInterval* dtitvsample[] = {
			new DateInterval(date1,date2),
            new DateInterval(date2,date3),
			new DateInterval(date3,date4),
        };
 	UnicodeString skeletons[] = {
            UnicodeString("yMMMd"),
            UnicodeString("MMMMd"),
            UnicodeString("jm"),
			0,
		};
    u_fprintf(out,"%-10s%-22s%-22s%-35s%-35s\n", "Skeleton","from","to","Date Interval in en_US","Date Interval in Ja");
	int i=0;
	UnicodeString formatEn,formatJa;
	FieldPosition pos=0;
    for (int j=0;skeletons[j]!=NULL ;j++) {
 		 u_fprintf(out,"%-10S%-22S%-22S",skeletons[j].getTerminatedBuffer(),data[i].getTerminatedBuffer(),data[i+1].getTerminatedBuffer());
         //create a DateIntervalFormat instance for given skeleton, locale
		 DateIntervalFormat* dtitvfmtEn = DateIntervalFormat::createInstance(skeletons[j], Locale::getEnglish(),status);
         DateIntervalFormat* dtitvfmtJa = DateIntervalFormat::createInstance(skeletons[j], Locale::getJapanese(),status);
		 formatEn.remove();
		 formatJa.remove();
		 //get the DateIntervalFormat
		 dtitvfmtEn->format(dtitvsample[i],formatEn,pos,status);
		 dtitvfmtJa->format(dtitvsample[i],formatJa,pos,status);
         u_fprintf(out,"%-35S%-35S\n", formatEn.getTerminatedBuffer(),formatJa.getTerminatedBuffer());     
		 delete dtitvfmtEn;
		 delete dtitvfmtJa;
         i++;
        }
	u_fclose(out);
	//! [dtitvfmtPreDefined]
/* output of the sample code:
  *********************************************************************************************************************************************************
   Skeleton		from								to								Date Interval in en_US				Date Interval in Ja
   yMMMd			2007-10-10 10:10:10					2008-10-10 10:10:10				Nov 10, 2007 – Nov 10, 2008			2007年11月10日~2008年11月10日 
   MMMMd			2008-10-10 10:10:10					2008-11-10 10:10:10				November 10 – December 10			11月10日~12月10日 
   jm				2008-11-10 10:10:10					2008-11-10 15:10:10				10:10 AM – 3:10 PM					10:10~15:10

  *********************************************************************************************************************************************************/
}
std::string GlobalizationNDK::getDateNames(const std::string& args)
{
    ENamesType type = kNamesWide;
    ENamesItem item = kNamesMonths;

    if (!args.empty()) {
        Json::Reader reader;
        Json::Value root;
        bool parse = reader.parse(args, root);

        if (!parse) {
            slog2f(0, ID_G11N, SLOG2_ERROR, "GlobalizationNDK::getDateNames: invalid json data: %s",
                    args.c_str());
            return errorInJson(PARSING_ERROR, "Parameters not valid json format!");
        }

        Json::Value options = root["options"];

        std::string error;
        if (!handleNamesOptions(options, type, item, error))
            return errorInJson(PARSING_ERROR, error);
    }

    int count;
    const char* pattern;
    DateFormat::EStyle dstyle;

    // Check ICU SimpleDateFormat document for patterns for months and days.
    // http://www.icu-project.org/apiref/icu4c/classicu_1_1SimpleDateFormat.html
    if (item == kNamesMonths) {
        count = 12;
        if (type == kNamesWide) {
            dstyle = DateFormat::kLong;
            pattern = "MMMM";
        } else {
            dstyle = DateFormat::kShort;
            pattern = "MMM";
        }
    } else {
        count = 7;
        if (type == kNamesWide) {
            dstyle = DateFormat::kLong;
            pattern = "eeee";
        } else {
            dstyle = DateFormat::kShort;
            pattern = "eee";
        }
    }

    UErrorCode status = U_ZERO_ERROR;
    const Locale& loc = Locale::getDefault();
    DateFormat* df = DateFormat::createDateInstance(dstyle, loc);

    if (!df) {
        slog2f(0, ID_G11N, SLOG2_ERROR, "GlobalizationNDK::getDateNames: unable to create DateFormat instance!");
        return errorInJson(UNKNOWN_ERROR, "Unable to create DateFormat instance!");
    }
    std::auto_ptr<DateFormat> deleter(df);

    if (df->getDynamicClassID() != SimpleDateFormat::getStaticClassID()) {
        slog2f(0, ID_G11N, SLOG2_ERROR, "GlobalizationNDK::getDateNames: DateFormat instance not SimpleDateFormat!");
        return errorInJson(UNKNOWN_ERROR, "DateFormat instance not SimpleDateFormat!");
    }

    SimpleDateFormat* sdf = (SimpleDateFormat*) df;
    sdf->applyLocalizedPattern(UnicodeString(pattern, -1), status);

    Calendar* cal = Calendar::createInstance(status);
    if (!cal) {
        slog2f(0, ID_G11N, SLOG2_ERROR, "GlobalizationNDK::getDateNames: unable to create Calendar instance: %x.",
                status);
        return errorInJson(UNKNOWN_ERROR, "Unable to create Calendar instance!");
    }
    std::auto_ptr<Calendar> caldeleter(cal);

    UCalendarDaysOfWeek ud = cal->getFirstDayOfWeek(status);
    if (status != U_ZERO_ERROR && status != U_ERROR_WARNING_START) {
        slog2f(0, ID_G11N, SLOG2_ERROR, "GlobalizationNDK::getDateNames: failed to getFirstDayOfWeek: %d!",
                status);
        return errorInJson(PARSING_ERROR, "Failed to getFirstDayOfWeek!");
    }

    if (ud == UCAL_SUNDAY)
        cal->set(2014, 0, 5);
    else
        cal->set(2014, 0, 6);

    std::list<std::string> utf8Names;

    for (int i = 0; i < count; ++i) {
        UnicodeString ucs;
        sdf->format(cal->getTime(status), ucs);

        if (item == kNamesMonths)
            cal->add(UCAL_MONTH, 1, status);
        else
            cal->add(UCAL_DAY_OF_MONTH, 1, status);

        if (ucs.isEmpty())
            continue;

        std::string utf8;
        ucs.toUTF8String(utf8);
        utf8Names.push_back(utf8);
    }

    if (!utf8Names.size()) {
        slog2f(0, ID_G11N, SLOG2_ERROR, "GlobalizationNDK::getDateNames: unable to get symbols: item: %d, type: %d.",
                item, type);
        return errorInJson(UNKNOWN_ERROR, "Unable to get symbols!");
    }

    return resultInJson(utf8Names);
}