Exemple #1
0
/**
 * @bug 4103341
 */
void DateFormatRegressionTest::Test4103341(void) 
{
    TimeZone *saveZone  =TimeZone::createDefault();
    //try {
        
    // {sfb} changed from setDefault to adoptDefault
    TimeZone::adoptDefault(TimeZone::createTimeZone("CST"));
    UErrorCode status = U_ZERO_ERROR;
    SimpleDateFormat *simple = new SimpleDateFormat(UnicodeString("MM/dd/yyyy HH:mm"), status);
    if(U_FAILURE(status)) {
      dataerrln("Couldn't create SimpleDateFormat, error %s", u_errorName(status));
      delete simple;
      return;
    }
    failure(status, "new SimpleDateFormat");
    TimeZone *temp = TimeZone::createDefault();
    if(simple->getTimeZone() != *temp)
            errln("Fail: SimpleDateFormat not using default zone");
    //}
    //finally {
        TimeZone::adoptDefault(saveZone);
    //}

    delete temp;
    delete simple;
}
Exemple #2
0
/**
 * @bug 4089106
 */
void DateFormatRegressionTest::Test4089106(void) 
{
    TimeZone *def = TimeZone::createDefault();
    //try {
        TimeZone *z = new SimpleTimeZone((int)(1.25 * 3600000), "FAKEZONE");
        TimeZone::setDefault(*z);
        UErrorCode status = U_ZERO_ERROR;
        SimpleDateFormat *f = new SimpleDateFormat(status);
        if(U_FAILURE(status)) {
          dataerrln("Couldn't create SimpleDateFormat, error %s", u_errorName(status));
          delete f;
          delete def;
          delete z;
          return;
        }
        failure(status, "new SimpleDateFormat");
        if (f->getTimeZone()!= *z)
            errln("Fail: SimpleTimeZone should use TimeZone.getDefault()");
        
        //}
    //finally {
        TimeZone::setDefault(*def);
    //}

    delete z;
    delete f;
    delete def;
}
Exemple #3
0
status_t
BFormattingConventions::GetDateFormat(BDateFormatStyle style,
                                      BString& outFormat) const
{
    if (style < 0 || style >= B_DATE_FORMAT_STYLE_COUNT)
        return B_BAD_VALUE;

    outFormat = fExplicitDateFormats[style].Length()
                ? fExplicitDateFormats[style]
                : fCachedDateFormats[style];

    if (outFormat.Length() > 0)
        return B_OK;

    ObjectDeleter<DateFormat> dateFormatter(
        DateFormat::createDateInstance((DateFormat::EStyle)style, *fICULocale));
    if (dateFormatter.Get() == NULL)
        return B_NO_MEMORY;

    SimpleDateFormat* dateFormatterImpl
        = static_cast<SimpleDateFormat*>(dateFormatter.Get());

    UnicodeString icuString;
    dateFormatterImpl->toPattern(icuString);
    BStringByteSink stringConverter(&outFormat);
    icuString.toUTF8(stringConverter);

    fCachedDateFormats[style] = outFormat;

    return B_OK;
}
Exemple #4
0
/**
 * @bug 4104522
 * CANNOT REPRODUCE
 * According to the bug report, this test should throw a
 * StringIndexOutOfBoundsException during the second parse.  However,
 * this is not seen.
 */
void DateFormatRegressionTest::Test4104522(void) 
{
    UErrorCode status = U_ZERO_ERROR;
    
    SimpleDateFormat *sdf = new SimpleDateFormat(status);
    if(U_FAILURE(status)) {
      dataerrln("Couldn't create SimpleDateFormat, error %s", u_errorName(status));
      delete sdf;
      return;
    }
    failure(status, "new SimpleDateFormat");
    UnicodeString pattern = "'time' hh:mm";
    sdf->applyPattern(pattern);
    logln("pattern: \"" + pattern + "\"");

    // works correctly
    ParsePosition pp(0);
    UnicodeString text = "time ";
    UDate dt = sdf->parse(text, pp);
    logln(" text: \"" + text + "\"" +
          " date: " + dt);

    // works wrong
    pp.setIndex(0);
    text = "time";
    dt = sdf->parse(text, pp);
    logln(" text: \"" + text + "\"" +
          " date: " + dt);

    delete sdf;
}
Exemple #5
0
std::string L10n::FormatMillisecondsIntoDateString(const UDate& milliseconds, const std::string& formatString) const
{
	UErrorCode status = U_ZERO_ERROR;
	UnicodeString dateString;
	std::string resultString;

	UnicodeString unicodeFormat = UnicodeString::fromUTF8(formatString.c_str());
	SimpleDateFormat* dateFormat = new SimpleDateFormat(unicodeFormat, status);
	if (U_FAILURE(status))
		LOGERROR("Error creating SimpleDateFormat: %s", u_errorName(status));

	const TimeZone* timeZone = TimeZone::getGMT();

	status = U_ZERO_ERROR;
	Calendar* calendar = Calendar::createInstance(*timeZone, currentLocale, status);
	if (U_FAILURE(status))
		LOGERROR("Error creating calendar: %s", u_errorName(status));
   
	dateFormat->adoptCalendar(calendar);
	dateFormat->format(milliseconds, dateString);
	delete dateFormat;

	dateString.toUTF8String(resultString);
	return resultString;
}
Exemple #6
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;
}
Exemple #7
0
/**
 * @bug 4061287
 */
void DateFormatRegressionTest::Test4061287(void) 
{
    UErrorCode status = U_ZERO_ERROR;
    
    SimpleDateFormat *df = new SimpleDateFormat(UnicodeString("dd/MM/yyyy"), status);
    if (U_FAILURE(status)) {
        dataerrln("Fail new SimpleDateFormat: %s", u_errorName(status));
        delete df;
        return;
    }
    failure(status, "new SimpleDateFormat");
    //try {
    logln(UnicodeString("") + df->parse("35/01/1971", status));  
    failure(status, "df->parse(\"35/01/1971\")");
    //logln(df.parse("35/01/1971").toString());
    //}
    /*catch (ParseException e) {
        errln("Fail: " + e);
        e.printStackTrace();
    }*/
    df->setLenient(FALSE);
    UBool ok = FALSE;
    //try {
    logln(UnicodeString("") + df->parse("35/01/1971", status));
    if(U_FAILURE(status))
        ok = TRUE;
    //logln(df.parse("35/01/1971").toString());
    //} catch (ParseException e) {ok=TRUE;}
    if(!ok) 
        errln("Fail: Lenient not working");
    delete df;
}
Exemple #8
0
void
IntlTestDateFormat::describeTest()
{
    // Assume it's a SimpleDateFormat and get some info
    SimpleDateFormat *s = (SimpleDateFormat*)fFormat;
    UnicodeString str;
    logln(fTestName + " Pattern " + s->toPattern(str));
}
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]
}
std::string GlobalizationNDK::getDatePattern(const std::string& args)
{
    DateFormat::EStyle dstyle = DateFormat::kShort, tstyle = DateFormat::kShort;

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

        if (!parse) {
            slog2f(0, ID_G11N, SLOG2_ERROR, "GlobalizationNDK::getDatePattern: 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 (!handleDateOptions(options, dstyle, tstyle, error))
            return errorInJson(PARSING_ERROR, error);
    }

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

    if (!df) {
        slog2f(0, ID_G11N, SLOG2_ERROR, "GlobalizationNDK::getDatePattern: 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::getDatePattern: DateFormat instance not SimpleDateFormat!");
        return errorInJson(UNKNOWN_ERROR, "DateFormat instance not SimpleDateFormat!");
    }

    SimpleDateFormat* sdf = (SimpleDateFormat*) df;

    UnicodeString pt;
    sdf->toPattern(pt);
    std::string ptUtf8;
    pt.toUTF8String(ptUtf8);

    const TimeZone& tz = sdf->getTimeZone();

    UnicodeString tzName;
    tz.getDisplayName(tzName);
    std::string tzUtf8;
    tzName.toUTF8String(tzUtf8);

    int utc_offset = tz.getRawOffset() / 1000; // UTC_OFFSET in seconds.
    int dst_offset = tz.getDSTSavings() / 1000; // DST_OFFSET in seconds;

    return resultInJson(ptUtf8, tzUtf8, utc_offset, dst_offset);
}
Exemple #11
0
/**
 * @bug 4104136
 */
void DateFormatRegressionTest::Test4104136(void) 
{
    UErrorCode status = U_ZERO_ERROR;
    SimpleDateFormat *sdf = new SimpleDateFormat(status); 
    if(U_FAILURE(status)) {
      dataerrln("Couldn't create SimpleDateFormat, error %s", u_errorName(status));
      delete sdf;
      return;
    }
    if(failure(status, "new SimpleDateFormat")) return;
    UnicodeString pattern = "'time' hh:mm"; 
    sdf->applyPattern(pattern); 
    logln("pattern: \"" + pattern + "\""); 

    UnicodeString strings [] = {
        (UnicodeString)"time 10:30",
        (UnicodeString) "time 10:x",
        (UnicodeString) "time 10x"
    };

    ParsePosition ppos [] = {
        ParsePosition(10),
        ParsePosition(0),
        ParsePosition(0)
    };

    UDate dates [] = {
        date(70, UCAL_JANUARY, 1, 10, 30),
        -1,
        -1
    };

    /*Object[] DATA = {
        "time 10:30", new ParsePosition(10), new Date(70, Calendar.JANUARY, 1, 10, 30),
        "time 10:x", new ParsePosition(0), null,
        "time 10x", new ParsePosition(0), null,
    };*/
    
    for(int i = 0; i < 3; i++) {
        UnicodeString text = strings[i];
        ParsePosition finish = ppos[i];
        UDate exp = dates[i];
        
        ParsePosition pos(0);
        UDate d = sdf->parse(text, pos);
        logln(" text: \"" + text + "\""); 
        logln(" index: %d", pos.getIndex()); 
        logln((UnicodeString) " result: " + d);
        if(pos.getIndex() != finish.getIndex())
            errln("Fail: Expected pos " + finish.getIndex());
        if (! ((d == 0 && exp == -1) || (d == exp)))
            errln((UnicodeString) "Fail: Expected result " + exp);
    }

    delete sdf;
}
Exemple #12
0
void
BCountry::SetTimeFormat(const char* formatString, bool longFormat)
{
    icu_4_2::DateFormat* dateFormatter
        = longFormat ? fICULongTimeFormatter : fICUShortTimeFormatter;
    SimpleDateFormat* dateFormatterImpl
        = static_cast<SimpleDateFormat*>(dateFormatter);

    UnicodeString pattern(formatString);
    dateFormatterImpl->applyPattern(pattern);
}
Exemple #13
0
/**
 * @bug 4056591
 * Verify the function of the [s|g]et2DigitYearStart() API.
 */
void DateFormatRegressionTest::Test4056591(void) 
{
    UErrorCode status = U_ZERO_ERROR;

    //try {
        SimpleDateFormat *fmt = new SimpleDateFormat(UnicodeString("yyMMdd"), Locale::getUS(), status);
        if (failure(status, "new SimpleDateFormat", TRUE)) {
            delete fmt;
            return;
        }
        UDate start = date(1809-1900, UCAL_DECEMBER, 25);
        fmt->set2DigitYearStart(start, status);
        failure(status, "fmt->setTwoDigitStartDate");
        if( (fmt->get2DigitYearStart(status) != start) || failure(status, "get2DigitStartDate"))
            errln("get2DigitYearStart broken");
        UDate dates [] = {
            date(1809-1900, UCAL_DECEMBER, 25),
            date(1909-1900, UCAL_DECEMBER, 24),
            date(1809-1900, UCAL_DECEMBER, 26),
            date(1861-1900, UCAL_DECEMBER, 25),
        };

        UnicodeString strings [] = {
            (UnicodeString) "091225",
            (UnicodeString) "091224",
            (UnicodeString) "091226",
            (UnicodeString) "611225"
        };

        /*Object[] DATA = {
            "091225", new Date(1809-1900, Calendar.DECEMBER, 25),
            "091224", new Date(1909-1900, Calendar.DECEMBER, 24),
            "091226", new Date(1809-1900, Calendar.DECEMBER, 26),
            "611225", new Date(1861-1900, Calendar.DECEMBER, 25),
        };*/

        for(int i = 0; i < 4; i++) {
            UnicodeString s = strings[i];
            UDate exp = dates[i];
            UDate got = fmt->parse(s, status);
            failure(status, "fmt->parse");
            logln(s + " -> " + got + "; exp " + exp);
            if(got != exp) 
                errln("set2DigitYearStart broken");
        }
    /*}
    catch (ParseException e) {
        errln("Fail: " + e);
        e.printStackTrace();
    }*/

    delete fmt;
}
Exemple #14
0
RelativeDateFormat::RelativeDateFormat( UDateFormatStyle timeStyle, UDateFormatStyle dateStyle,
                                        const Locale& locale, UErrorCode& status) :
 DateFormat(), fDateTimeFormatter(NULL), fDatePattern(), fTimePattern(), fCombinedFormat(NULL),
 fDateStyle(dateStyle), fLocale(locale), fDatesLen(0), fDates(NULL),
 fCombinedHasDateAtStart(FALSE), fCapitalizationInfoSet(FALSE),
 fCapitalizationOfRelativeUnitsForUIListMenu(FALSE), fCapitalizationOfRelativeUnitsForStandAlone(FALSE),
 fCapitalizationBrkIter(NULL)
{
    if(U_FAILURE(status) ) {
        return;
    }

    if (timeStyle < UDAT_NONE || timeStyle > UDAT_SHORT) {
        // don't support other time styles (e.g. relative styles), for now
        status = U_ILLEGAL_ARGUMENT_ERROR;
        return;
    }
    UDateFormatStyle baseDateStyle = (dateStyle > UDAT_SHORT)? (UDateFormatStyle)(dateStyle & ~UDAT_RELATIVE): dateStyle;
    DateFormat * df;
    // Get fDateTimeFormatter from either date or time style (does not matter, we will override the pattern).
    // We do need to get separate patterns for the date & time styles.
    if (baseDateStyle != UDAT_NONE) {
        df = createDateInstance((EStyle)baseDateStyle, locale);
        fDateTimeFormatter=dynamic_cast<SimpleDateFormat *>(df);
        if (fDateTimeFormatter == NULL) {
            status = U_UNSUPPORTED_ERROR;
             return;
        }
        fDateTimeFormatter->toPattern(fDatePattern);
        if (timeStyle != UDAT_NONE) {
            df = createTimeInstance((EStyle)timeStyle, locale);
            SimpleDateFormat *sdf = dynamic_cast<SimpleDateFormat *>(df);
            if (sdf != NULL) {
                sdf->toPattern(fTimePattern);
                delete sdf;
            }
        }
    } else {
        // does not matter whether timeStyle is UDAT_NONE, we need something for fDateTimeFormatter
        df = createTimeInstance((EStyle)timeStyle, locale);
        fDateTimeFormatter=dynamic_cast<SimpleDateFormat *>(df);
        if (fDateTimeFormatter == NULL) {
            status = U_UNSUPPORTED_ERROR;
            delete df;
            return;
        }
        fDateTimeFormatter->toPattern(fTimePattern);
    }

    // Initialize the parent fCalendar, so that parse() works correctly.
    initializeCalendar(NULL, locale, status);
    loadDates(status);
}
Exemple #15
0
/**
 * @bug 4060212
 */
void DateFormatRegressionTest::Test4060212(void) 
{
    UnicodeString dateString = "1995-040.05:01:29";

    logln( "dateString= " + dateString );
    logln("Using yyyy-DDD.hh:mm:ss");
    UErrorCode status = U_ZERO_ERROR;
    SimpleDateFormat *formatter = new SimpleDateFormat(UnicodeString("yyyy-DDD.hh:mm:ss"), status);
    if (failure(status, "new SimpleDateFormat", TRUE)) return;
    ParsePosition pos(0);
    UDate myDate = formatter->parse( dateString, pos );
    UnicodeString myString;
    DateFormat *fmt = DateFormat::createDateTimeInstance( DateFormat::FULL,
                                                            DateFormat::LONG);
    if (fmt == NULL) {
        dataerrln("Error calling DateFormat::createDateTimeInstance");
        delete formatter;
        return;
    }

    myString = fmt->format( myDate, myString);
    logln( myString );

    Calendar *cal = new GregorianCalendar(status);
    failure(status, "new GregorianCalendar");
    cal->setTime(myDate, status);
    failure(status, "cal->setTime");
    if ((cal->get(UCAL_DAY_OF_YEAR, status) != 40) || failure(status, "cal->get"))
        errln((UnicodeString) "Fail: Got " + cal->get(UCAL_DAY_OF_YEAR, status) +
                            " Want 40");

    // this is an odd usage of "ddd" and it doesn't
    // work now that date values are range checked per #3579.
    logln("Using yyyy-ddd.hh:mm:ss");
    delete formatter;
    formatter = NULL;
    formatter = new SimpleDateFormat(UnicodeString("yyyy-ddd.hh:mm:ss"), status);
    if(failure(status, "new SimpleDateFormat")) return;
    pos.setIndex(0);
    myDate = formatter->parse( dateString, pos );
    myString = fmt->format( myDate, myString );
    logln( myString );
    cal->setTime(myDate, status);
    failure(status, "cal->setTime");
    if ((cal->get(UCAL_DAY_OF_YEAR, status) != 40) || failure(status, "cal->get"))
        errln((UnicodeString) "Fail: Got " + cal->get(UCAL_DAY_OF_YEAR, status) +
                            " Want 40");

    delete formatter;
    delete fmt;
    delete cal;
}
Exemple #16
0
 // Constructor that takes the actual patterns for hour-minute,
 // minute-second, and hour-minute-second respectively.
 NumericDateFormatters(
         const UnicodeString &hm,
         const UnicodeString &ms,
         const UnicodeString &hms,
         UErrorCode &status) : 
         hourMinute(hm, status),
         minuteSecond(ms, status), 
         hourMinuteSecond(hms, status) {
     const TimeZone *gmt = TimeZone::getGMT();
     hourMinute.setTimeZone(*gmt);
     minuteSecond.setTimeZone(*gmt);
     hourMinuteSecond.setTimeZone(*gmt);
 }
Exemple #17
0
status_t
BFormattingConventions::GetTimeFormat(BTimeFormatStyle style,
                                      BString& outFormat) const
{
    if (style < 0 || style >= B_TIME_FORMAT_STYLE_COUNT)
        return B_BAD_VALUE;

    outFormat = fExplicitTimeFormats[style].Length()
                ? fExplicitTimeFormats[style]
                : fCachedTimeFormats[style];

    if (outFormat.Length() > 0)
        return B_OK;

    ObjectDeleter<DateFormat> timeFormatter(
        DateFormat::createTimeInstance((DateFormat::EStyle)style, *fICULocale));
    if (timeFormatter.Get() == NULL)
        return B_NO_MEMORY;

    SimpleDateFormat* timeFormatterImpl
        = static_cast<SimpleDateFormat*>(timeFormatter.Get());

    UnicodeString icuString;
    timeFormatterImpl->toPattern(icuString);
    BStringByteSink stringConverter(&outFormat);
    icuString.toUTF8(stringConverter);

    int8 use24HourClock = fExplicitUse24HourClock != CLOCK_HOURS_UNSET
                          ?  fExplicitUse24HourClock : fCachedUse24HourClock;
    if (use24HourClock != CLOCK_HOURS_UNSET) {
        // adjust to 12/24-hour clock as requested
        bool localeUses24HourClock = !FormatUsesAmPm(outFormat);
        if (localeUses24HourClock) {
            if (use24HourClock == CLOCK_HOURS_12)
                CoerceFormatTo12HourClock(outFormat);
        } else {
            if (use24HourClock == CLOCK_HOURS_24)
                CoerceFormatTo24HourClock(outFormat);
        }
    }

    // use abbreviated timezone in short timezone format
    CoerceFormatToAbbreviatedTimezone(outFormat);

    fCachedTimeFormats[style] = outFormat;

    return B_OK;
}
Exemple #18
0
UnicodeString&
RelativeDateFormat::toPatternTime(UnicodeString& result, UErrorCode& status) const
{
    if (!U_FAILURE(status)) {
        result.remove();
        if ( fTimeFormat ) {
            SimpleDateFormat* sdtfmt = dynamic_cast<SimpleDateFormat*>(fTimeFormat);
            if (sdtfmt != NULL) {
                sdtfmt->toPattern(result);
            } else {
                status = U_UNSUPPORTED_ERROR;
            }
        }
    }
    return result;
}
Exemple #19
0
/**
 * @bug 4134203
 * SimpleDateFormat won't parse "GMT"
 */
void DateFormatRegressionTest::Test4134203(void) 
{
    UErrorCode status = U_ZERO_ERROR;
    UnicodeString dateFormat = "MM/dd/yy HH:mm:ss zzz";
    SimpleDateFormat *fmt = new SimpleDateFormat(dateFormat, status);
    if (failure(status, "new SimpleDateFormat", TRUE)) return;
    ParsePosition p0(0);
    UDate d = fmt->parse("01/22/92 04:52:00 GMT", p0);
    logln(dateToString(d));
    if(p0 == ParsePosition(0))
        errln("Fail: failed to parse 'GMT'");
    // In the failure case an exception is thrown by parse();
    // if no exception is thrown, the test passes.

    delete fmt;
}
Exemple #20
0
/*
Function:
InvokeCallbackForDatePattern

Gets the ICU date pattern for the specified locale and EStyle and invokes the callback with the result.
*/
bool InvokeCallbackForDatePattern(Locale& locale, DateFormat::EStyle style, EnumCalendarInfoCallback callback, const void* context)
{
	LocalPointer<DateFormat> dateFormat(DateFormat::createDateInstance(style, locale));
	if (dateFormat.isNull())
		return false;

	// cast to SimpleDateFormat so we can call toPattern()  
	SimpleDateFormat* sdf = dynamic_cast<SimpleDateFormat*>(dateFormat.getAlias());
	if (sdf == NULL)
		return false;

	UnicodeString pattern;
	sdf->toPattern(pattern);

	callback(pattern.getTerminatedBuffer(), context);
	return true;
}
Exemple #21
0
bool
BCountry::TimeFormat(BString& format, bool longFormat) const
{
    icu_4_2::DateFormat* dateFormatter;
    dateFormatter = longFormat ? fICULongTimeFormatter : fICUShortTimeFormatter;
    SimpleDateFormat* dateFormatterImpl
        = static_cast<SimpleDateFormat*>(dateFormatter);

    UnicodeString ICUString;
    ICUString = dateFormatterImpl->toPattern(ICUString);

    BStringByteSink stringConverter(&format);

    ICUString.toUTF8(stringConverter);

    return true;
}
DateIntervalFormat::DateIntervalFormat(const Locale& locale,
                                       DateIntervalInfo* dtItvInfo,
                                       const UnicodeString* skeleton,
                                       UErrorCode& status) 
:   fInfo(NULL),
    fDateFormat(NULL),
    fFromCalendar(NULL),
    fToCalendar(NULL),
    fDtpng(NULL)
{
    if ( U_FAILURE(status) ) {
        delete dtItvInfo;
        return;
    }
    fDtpng = DateTimePatternGenerator::createInstance(locale, status);
    SimpleDateFormat* dtfmt = createSDFPatternInstance(*skeleton, locale, 
                                                    fDtpng, status);
    if ( U_FAILURE(status) ) {
        delete dtItvInfo;
        delete fDtpng;
        delete dtfmt;
        return;
    }
    if ( dtfmt == NULL || dtItvInfo == NULL || fDtpng == NULL ) {
        status = U_MEMORY_ALLOCATION_ERROR;
        // safe to delete NULL
        delete dtfmt;
        delete dtItvInfo;
        delete fDtpng;
        return;
    }
    if ( skeleton ) {
        fSkeleton = *skeleton;
    }
    fInfo = dtItvInfo;
    fDateFormat = dtfmt;
    if ( dtfmt->getCalendar() ) {
        fFromCalendar = dtfmt->getCalendar()->clone();
        fToCalendar = dtfmt->getCalendar()->clone();
    } else {
        fFromCalendar = NULL;
        fToCalendar = NULL;
    }
    initializePattern(status);
}
Exemple #23
0
/**
 * @bug 4151631
 * SimpleDateFormat incorrect handling of 2 single quotes in format()
 */
void DateFormatRegressionTest::Test4151631(void) 
{
    UnicodeString pattern = "'TO_DATE('''dd'-'MM'-'yyyy HH:mm:ss''' , ''DD-MM-YYYY HH:MI:SS'')'";
    logln("pattern=" + pattern);
    UErrorCode status = U_ZERO_ERROR;
    SimpleDateFormat *format = new SimpleDateFormat(pattern, Locale::getUS(), status);
    if (failure(status, "new SimpleDateFormat", TRUE)) return;
    UnicodeString result;
    FieldPosition pos(FieldPosition::DONT_CARE);
    result = format->format(date(1998-1900, UCAL_JUNE, 30, 13, 30, 0), result, pos);
    if (result != "TO_DATE('30-06-1998 13:30:00' , 'DD-MM-YYYY HH:MI:SS')") {
        errln("Fail: result=" + result);
    }
    else {
        logln("Pass: result=" + result);
    }

    delete format;
}
Exemple #24
0
bool
BCountry::TimeFormat(BString& format, bool longFormat) const
{
	icu_4_2::DateFormat* dateFormatter;
 	dateFormatter = DateFormat::createTimeInstance(
		longFormat ? DateFormat::FULL : DateFormat::SHORT,
		*fICULocale);
	SimpleDateFormat* dateFormatterImpl
		= static_cast<SimpleDateFormat*>(dateFormatter);

	UnicodeString ICUString;
	ICUString = dateFormatterImpl->toPattern(ICUString);

	BStringByteSink stringConverter(&format);

	ICUString.toUTF8(stringConverter);

	return true;
}
status_t
BFormattingConventions::GetDateTimeFormat(BDateFormatStyle dateStyle,
	BTimeFormatStyle timeStyle, BString& outFormat) const
{
	if (dateStyle < 0 || dateStyle >= B_DATE_FORMAT_STYLE_COUNT)
		return B_BAD_VALUE;

	if (timeStyle < 0 || timeStyle >= B_TIME_FORMAT_STYLE_COUNT)
		return B_BAD_VALUE;

	outFormat = fExplicitDateTimeFormats[dateStyle][timeStyle].Length()
		? fExplicitDateTimeFormats[dateStyle][timeStyle]
		: fCachedDateTimeFormats[dateStyle][timeStyle];

	if (outFormat.Length() > 0)
		return B_OK;

	ObjectDeleter<DateFormat> dateFormatter(
		DateFormat::createDateTimeInstance((DateFormat::EStyle)dateStyle,
			(DateFormat::EStyle)timeStyle, *fICULocale));
	if (dateFormatter.Get() == NULL)
		return B_NO_MEMORY;

	SimpleDateFormat* dateFormatterImpl
		= static_cast<SimpleDateFormat*>(dateFormatter.Get());

	UnicodeString icuString;
	dateFormatterImpl->toPattern(icuString);
	BStringByteSink stringConverter(&outFormat);
	icuString.toUTF8(stringConverter);

	CoerceFormatForClock(outFormat);

	if (dateStyle != B_FULL_DATE_FORMAT) {
		// use abbreviated timezone in short timezone format
		CoerceFormatToAbbreviatedTimezone(outFormat);
	}

	fCachedDateTimeFormats[dateStyle][timeStyle] = outFormat;

	return B_OK;
}
Exemple #26
0
/**
 * @bug 4101483
 */
void DateFormatRegressionTest::Test4101483(void) 
{
    UErrorCode status = U_ZERO_ERROR;
    SimpleDateFormat *sdf = new SimpleDateFormat(UnicodeString("z"), Locale::getUS(), status);
    if (failure(status, "new SimpleDateFormat", TRUE)) return;
    FieldPosition fp(UDAT_TIMEZONE_FIELD);
    //Date d = date(9234567890L);
    UDate d = 9234567890.0;
    //StringBuffer buf = new StringBuffer("");
    UnicodeString buf;
    sdf->format(d, buf, fp);
    //logln(sdf.format(d, buf, fp).toString());
    logln(dateToString(d) + " => " + buf);
    logln("beginIndex = " + fp.getBeginIndex());
    logln("endIndex = " + fp.getEndIndex());
    if (fp.getBeginIndex() == fp.getEndIndex()) 
        errln("Fail: Empty field");

    delete sdf;
}
Exemple #27
0
/**
 * @bug 4029195
 */
void DateFormatRegressionTest::Test4029195(void) 
{
    UErrorCode status = U_ZERO_ERROR;

    UDate today = Calendar::getNow();
    logln((UnicodeString) "today: " + today);

    SimpleDateFormat *sdf = (SimpleDateFormat*) DateFormat::createDateInstance();
    if (failure(status, "SimpleDateFormat::createDateInstance")) {
        return;
    }
    UnicodeString pat;
    if(sdf == NULL){
        dataerrln("Error calling DateFormat::createDateTimeInstance");
        return;
    }

    pat = sdf->toPattern(pat);
    logln("pattern: " + pat);
    UnicodeString fmtd;
    FieldPosition pos(FieldPosition::DONT_CARE);
    fmtd = sdf->format(today, fmtd, pos);
    logln("today: " + fmtd);

    sdf->applyPattern("G yyyy DDD");
    UnicodeString todayS;
    todayS = sdf->format(today, todayS, pos);
    logln("today: " + todayS);
    //try {
        today = sdf->parse(todayS, status);
        failure(status, "sdf->parse");
        logln((UnicodeString)"today date: " + today);
    /*} catch(Exception e) {
        logln("Error reparsing date: " + e.getMessage());
    }*/

    //try {
        UnicodeString rt;
        rt = sdf->format(sdf->parse(todayS, status), rt, pos);
        failure(status, "sdf->parse");
        logln("round trip: " + rt);
        if(rt != todayS) 
            errln("Fail: Want " + todayS + " Got " + rt);
    /*}
    catch (ParseException e) {
        errln("Fail: " + e);
        e.printStackTrace();
    }*/

    delete sdf;
}
DateFormat*
BLocale::_CreateTimeFormatter(const BString& format) const
{
	Locale* icuLocale
		= fConventions.UseStringsFromPreferredLanguage()
			? BLanguage::Private(&fLanguage).ICULocale()
			: BFormattingConventions::Private(&fConventions).ICULocale();

	DateFormat* timeFormatter
		= DateFormat::createTimeInstance(DateFormat::kShort, *icuLocale);
	if (timeFormatter == NULL)
		return NULL;

	SimpleDateFormat* timeFormatterImpl
		= static_cast<SimpleDateFormat*>(timeFormatter);

	UnicodeString pattern(format.String());
	timeFormatterImpl->applyPattern(pattern);

	return timeFormatter;
}
Exemple #29
0
string DateTimeFormat::StyleFormatter::getPattern(Locale *locale) {
    DateFormat *f = NULL;
    switch (iType) {
        case DATE:
            f = DateFormat::getDateInstance(iDateStyle, locale);
            break;
        case TIME:
            f = DateFormat::getTimeInstance(iTimeStyle, locale);
            break;
        case DATETIME:
            f = DateFormat::getDateTimeInstance(iDateStyle, iTimeStyle, locale);
            break;
    }
    
    SimpleDateFormat *sdf = dynamic_cast<SimpleDateFormat*>(f);
    
    if (sdf != 0) {
        throw IllegalArgumentException("No datetime pattern for locale: " + locale);
    }
    return sdf->toPattern();
}
std::string GlobalizationNDK::isDayLightSavingsTime(const std::string& args)
{
    if (args.empty()) {
        slog2f(0, ID_G11N, SLOG2_ERROR, "GlobalizationNDK::isDayLightSavingsTime: no date provided.");
        return errorInJson(UNKNOWN_ERROR, "No date is provided!");
    }

    Json::Reader reader;
    Json::Value root;
    bool parse = reader.parse(args, root);

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

    Json::Value dv = root["date"];

    if (!dv.isNumeric()) {
        slog2f(0, ID_G11N, SLOG2_ERROR, "GlobalizationNDK::isDayLightSavingsTime: invalid date format: %d",
                dv.type());
        return errorInJson(PARSING_ERROR, "Invalid date format!");
    }

    double date = dv.asDouble();

    UErrorCode status = U_ZERO_ERROR;
    SimpleDateFormat* sdf = new SimpleDateFormat(status);
    if (!sdf) {
        slog2f(0, ID_G11N, SLOG2_ERROR, "GlobalizationNDK::isDayLightSavingsTime: unable to create SimpleDateFormat instance: %d.",
                status);
        return errorInJson(UNKNOWN_ERROR, "Unable to create SimpleDateFormat instance!");
    }

    const TimeZone& tz = sdf->getTimeZone();
    bool result = tz.inDaylightTime(date, status);

    return resultInJson(result);
}