From af554b9e06d6b08a77161e5221a057010a5451ec Mon Sep 17 00:00:00 2001 From: Brian Lamb Date: Thu, 17 Sep 2015 11:53:23 -0700 Subject: [PATCH 1/2] Make NSLog output unicode characters to the debug output stream --- Frameworks/Foundation/NSLog.mm | 6 +++++- 1 file changed, 5 insertions(+), 1 deletion(-) diff --git a/Frameworks/Foundation/NSLog.mm b/Frameworks/Foundation/NSLog.mm index 25c95addd0..fd11a19840 100644 --- a/Frameworks/Foundation/NSLog.mm +++ b/Frameworks/Foundation/NSLog.mm @@ -21,7 +21,11 @@ void NSLogv(NSString *fmt, va_list list) { auto str = [[NSString alloc] initWithFormat:fmt arguments:list]; - OutputDebugStringA([str UTF8String]); OutputDebugStringA("\n"); + INT len = [str length]; + LPWSTR terminatedBuf = (LPWSTR) calloc(len + 1, sizeof(WCHAR)); + memcpy(terminatedBuf, [str rawCharacters], len * sizeof(WCHAR)); + OutputDebugStringW(terminatedBuf); OutputDebugStringW(L"\n"); + free(terminatedBuf); printf("%s\n", [str UTF8String]); [str release]; } From 7d608aa92b80b341ccfb8e1a2a8e9b7fe86f37ec Mon Sep 17 00:00:00 2001 From: Brian Lamb Date: Thu, 17 Sep 2015 11:57:06 -0700 Subject: [PATCH 2/2] - Initial rev of NSDateFormatter, NSLocale - Modify/standardize the way ICU is used across NSCalendar/NSDateFormatter/NSTimeZone --- Frameworks/Foundation/NSCalendar.mm | 81 +- Frameworks/Foundation/NSDateFormatter.mm | 557 +++++++- Frameworks/Foundation/NSLocale.mm | 105 ++ Frameworks/Foundation/NSNumberFormatter.mm | 4 - Frameworks/Foundation/NSTimeZone.mm | 65 +- Frameworks/include/NSCalendarInternal.h | 23 + Frameworks/include/NSLocaleInternal.h | 23 + Frameworks/include/NSTimeZoneInternal.h | 23 + .../Foundation.Shared.vcxitems | 1 + .../Foundation.Shared.vcxitems.filters | 1 + .../Foundation.Shared/Foundation.def | 2 + deps/prebuilt/include/icu/unicode/datefmt.h | 751 ++++++++++ deps/prebuilt/include/icu/unicode/dtfmtsym.h | 748 ++++++++++ deps/prebuilt/include/icu/unicode/dtptngen.h | 474 +++++++ deps/prebuilt/include/icu/unicode/smpdtfmt.h | 1238 +++++++++++++++++ deps/prebuilt/include/icu/unicode/udat.h | 997 +++++++++++++ deps/prebuilt/include/icu/unicode/udatpg.h | 586 ++++++++ include/Foundation/NSCalendar.h | 8 +- include/Foundation/NSDateFormatter.h | 44 +- include/Foundation/NSLocale.h | 1 + 20 files changed, 5658 insertions(+), 74 deletions(-) create mode 100644 Frameworks/Foundation/NSLocale.mm create mode 100644 Frameworks/include/NSCalendarInternal.h create mode 100644 Frameworks/include/NSLocaleInternal.h create mode 100644 Frameworks/include/NSTimeZoneInternal.h create mode 100644 deps/prebuilt/include/icu/unicode/datefmt.h create mode 100644 deps/prebuilt/include/icu/unicode/dtfmtsym.h create mode 100644 deps/prebuilt/include/icu/unicode/dtptngen.h create mode 100644 deps/prebuilt/include/icu/unicode/smpdtfmt.h create mode 100644 deps/prebuilt/include/icu/unicode/udat.h create mode 100644 deps/prebuilt/include/icu/unicode/udatpg.h diff --git a/Frameworks/Foundation/NSCalendar.mm b/Frameworks/Foundation/NSCalendar.mm index c2b03996b1..bd4256d84d 100644 --- a/Frameworks/Foundation/NSCalendar.mm +++ b/Frameworks/Foundation/NSCalendar.mm @@ -18,8 +18,9 @@ #include "Foundation/NSDate.h" #include "Foundation/NSString.h" #include "Foundation/NSCalendar.h" - -#define U_STATIC_IMPLEMENTATION 1 +#include "NSCalendarInternal.h" +#include "NSTimeZoneInternal.h" +#include "NSLocaleInternal.h" #include @@ -27,19 +28,51 @@ @implementation NSCalendar { NSString *_identifier; NSTimeZone *_timeZone; NSLocale *_locale; - icu_48::Calendar *_cal; + NSUInteger firstWeekDay, minimumDaysInFirstWeek; + BOOL firstWeekDaySet, minimumDaysInFirstWeekSet; + icu::Calendar *_cal; + BOOL _calendarNeedsRebuilding; } + -(icu::Calendar *) _getICUCalendar + { + if ( _cal == NULL || _calendarNeedsRebuilding ) { + _calendarNeedsRebuilding = FALSE; + if ( _cal ) delete _cal; + + UErrorCode status = U_ZERO_ERROR; + icu::Locale *locale = [_locale _createICULocale]; + icu::TimeZone *timeZone = [_timeZone _createICUTimeZone]; + + // No need to delete timeZone - GregorianCalendar adopts it + _cal = GregorianCalendar::createInstance(timeZone, *locale, status); + delete locale; + + if ( firstWeekDaySet ) { + _cal->setFirstDayOfWeek((UCalendarDaysOfWeek) firstWeekDay); + } + + if ( minimumDaysInFirstWeekSet ) { + _cal->setMinimalDaysInFirstWeek(minimumDaysInFirstWeek); + } + } + + return _cal; + } -(instancetype) copyWithZone:(NSZone*)zone { NSCalendar* result = [NSCalendar alloc]; result->_identifier= [_identifier copy]; result->_timeZone = [_timeZone copy]; result->_locale = [_locale copy]; - result->_cal = _cal->clone(); return result; } + -(icu::Calendar *) _createICUCalendar + { + return [self _getICUCalendar]->clone(); + } + +(NSCalendar*) currentCalendar { return [[[self alloc] initWithCalendarIdentifier:@"NSGregorianCalendar"] autorelease]; } @@ -47,8 +80,7 @@ +(NSCalendar*) currentCalendar { -(instancetype) initWithCalendarIdentifier:(NSString*)identifier { _identifier= [identifier copy]; _timeZone= [[NSTimeZone defaultTimeZone] copy]; - UErrorCode status = U_ZERO_ERROR; - _cal = GregorianCalendar::createInstance(status); + _locale = [[NSLocale currentLocale] retain]; return self; } @@ -56,7 +88,7 @@ -(void) dealloc { [_identifier release]; [_timeZone release]; [_locale release]; - delete _cal; + if ( _cal ) delete _cal; [super dealloc]; } @@ -66,11 +98,11 @@ -(NSString*) calendarIdentifier { } -(NSUInteger) firstWeekday { - return (NSUInteger) _cal->getFirstDayOfWeek(); + return (NSUInteger) [self _getICUCalendar]->getFirstDayOfWeek(); } -(NSUInteger) minimumDaysInFirstWeek { - return (NSUInteger) _cal->getMinimalDaysInFirstWeek(); + return (NSUInteger) [self _getICUCalendar]->getMinimalDaysInFirstWeek(); } -(NSTimeZone*) timeZone { @@ -82,30 +114,37 @@ -(NSLocale*) locale { } -(void) setFirstWeekday:(NSUInteger)weekday { - _cal->setFirstDayOfWeek((UCalendarDaysOfWeek) weekday); + firstWeekDay = weekday; + firstWeekDaySet = TRUE; + _calendarNeedsRebuilding = TRUE; } -(void) setMinimumDaysInFirstWeek:(NSUInteger)days { - _cal->setMinimalDaysInFirstWeek(days); + minimumDaysInFirstWeek = days; + minimumDaysInFirstWeekSet = TRUE; + _calendarNeedsRebuilding = TRUE; + } -(void) setTimeZone:(NSTimeZone*)timeZone { timeZone = [timeZone retain]; [_timeZone release]; _timeZone=timeZone; + _calendarNeedsRebuilding = TRUE; } -(void) setLocale:(NSLocale*)locale { locale = [locale retain]; [_locale release]; _locale=locale; + _calendarNeedsRebuilding = TRUE; } -(NSDate*) dateByAddingComponents:(NSDateComponents*)components toDate:(NSDate*)toDate options:(NSUInteger)options { double time = [toDate timeIntervalSince1970]; UErrorCode status = U_ZERO_ERROR; - Calendar *copy = _cal->clone(); + Calendar *copy = [self _getICUCalendar]->clone(); copy->setTime(time * 1000.0, status); NSInteger check; @@ -152,11 +191,11 @@ -(NSDate*) dateByAddingComponents:(NSDateComponents*)components toDate:(NSDate*) static Calendar *calendarCopyWithTZ(NSCalendar *self) { UErrorCode status = U_ZERO_ERROR; - Calendar *copy = self->_cal->clone(); + Calendar *copy = [self _getICUCalendar]->clone(); if ( self->_timeZone != nil ) { - icu::TimeZone* tz; - [self->_timeZone _getICUTimezone:&tz]; + icu::TimeZone* tz = [self->_timeZone _createICUTimeZone]; copy->setTimeZone(*tz); + delete tz; } return copy; @@ -165,13 +204,13 @@ -(NSDate*) dateByAddingComponents:(NSDateComponents*)components toDate:(NSDate*) static Calendar *calendarCopyWithTZAndDate(NSCalendar *self, NSDate *date) { UErrorCode status = U_ZERO_ERROR; - Calendar *copy = self->_cal->clone(); + Calendar *copy = [self _getICUCalendar]->clone(); copy->setTime([date timeIntervalSince1970] * 1000.0, status); if ( U_SUCCESS(status) ) { if ( self->_timeZone != nil ) { - icu::TimeZone* tz; - [self->_timeZone _getICUTimezone:&tz]; + icu::TimeZone* tz = [self->_timeZone _createICUTimeZone]; copy->setTimeZone(*tz); + delete tz; } return copy; @@ -312,12 +351,12 @@ -(NSRange) rangeOfUnit:(NSCalendarUnit)smaller inUnit:(NSCalendarUnit)larger for double time = [date timeIntervalSince1970]; UErrorCode status = U_ZERO_ERROR; - Calendar *copy = _cal->clone(); + Calendar *copy = [self _getICUCalendar]->clone(); copy->setTime(time * 1000.0, status); - icu::TimeZone *tz; - [_timeZone _getICUTimezone:&tz]; + icu::TimeZone *tz = [_timeZone _createICUTimeZone]; copy->setTimeZone(*tz); + delete tz; UCalendarDateFields icuSmaller = icuFieldFromUnit(smaller); ret.location = copy->getActualMinimum(icuSmaller, status); diff --git a/Frameworks/Foundation/NSDateFormatter.mm b/Frameworks/Foundation/NSDateFormatter.mm index f9455af316..264fdb88f1 100644 --- a/Frameworks/Foundation/NSDateFormatter.mm +++ b/Frameworks/Foundation/NSDateFormatter.mm @@ -15,7 +15,558 @@ //****************************************************************************** #include "Starboard.h" -#include "Foundation/NSDateFormatter.h" -@implementation NSDateFormatter -@end \ No newline at end of file +#import +#import +#import +#import +#include +#include +#include +#include + +#include +#include + +static icu::DateFormat::EStyle convertFormatterStyle(NSDateFormatterStyle fmt) +{ + switch ( fmt ) { + case NSDateFormatterShortStyle: + return icu::DateFormat::kShort; + case NSDateFormatterMediumStyle: + return icu::DateFormat::kMedium; + case NSDateFormatterLongStyle: + return icu::DateFormat::kLong; + case NSDateFormatterFullStyle: + return icu::DateFormat::kFull; + + default: + EbrDebugLog("Unrecognized formatter style, defaulting to UDAT_NONE.\n"); + case NSDateFormatterNoStyle: + return icu::DateFormat::kNone; + } +} + +class ICUPropertyValue +{ +public: + bool _boolValue; + idretaintype(NSObject) _objValue; + + ICUPropertyValue() + { + _boolValue = false; + } + + ICUPropertyValue(bool boolValue) + { + _boolValue = boolValue; + } + + ICUPropertyValue(NSObject *obj) + { + _objValue = obj; + } + + ICUPropertyValue(const ICUPropertyValue ©) + { + _boolValue = copy._boolValue; + _objValue = copy._objValue; + } +}; + +class ICUPropertyMapper +{ +public: + enum PropertyTypes + { + lenient, + amSymbol, + pmSymbol, + shortStandaloneWeekdaySymbols, + weekdaySymbols, + shortWeekdaySymbols, + standaloneWeekdaySymbols, + standaloneMonthSymbols, + monthSymbols + }; + +private: + typedef std::function PropertyFunctor; + +public: + PropertyFunctor _setProperty; + PropertyFunctor _getProperty; + PropertyTypes _type; + + ICUPropertyMapper() + { + } + + ICUPropertyMapper(const PropertyTypes type, const PropertyFunctor &setter, const PropertyFunctor &getter) : + _type(type), + _setProperty(setter), + _getProperty(getter) + { + } + + ICUPropertyMapper(const ICUPropertyMapper ©) + { + _type = copy._type; + _getProperty = copy._getProperty; + _setProperty = copy._setProperty; + } +}; + +static NSString *NSStringFromSymbol(icu::DateFormat *formatter, UDateFormatSymbolType symbol, int index, UErrorCode &error) +{ + uint32_t len = udat_getSymbols((UDateFormat *) formatter, (UDateFormatSymbolType) symbol, index, NULL, 0, &error); + UChar *strValue = (UChar *) calloc(len + 1, sizeof(UChar)); + error = U_ZERO_ERROR; + len = udat_getSymbols((UDateFormat *) formatter, (UDateFormatSymbolType) symbol, index, strValue, len + 1, &error); + NSString *ret = [NSString stringWithCharacters: (unichar *) strValue length: len]; + free(strValue); + + return ret; +} + +static NSArray *NSArrayFromSymbols(icu::DateFormat *formatter, UDateFormatSymbolType symbol, int startIdx, UErrorCode &error) +{ + uint32_t count = udat_countSymbols((UDateFormat *) formatter, symbol); + + NSMutableArray *symbolList = [NSMutableArray array]; + for ( int i = 0; i < count - startIdx; i ++ ) { + NSString *string = NSStringFromSymbol(formatter, symbol, i + startIdx, error); + if ( string == nil || error != U_ZERO_ERROR ) { + EbrDebugLog("Error retrieving symbol 0x%x index %d\n", symbol, i); + return nil; + } + [symbolList addObject: string]; + } + + NSArray *ret = [symbolList copy]; + [symbolList release]; + return ret; +} + +static void SetSymbolFromNSString(icu::DateFormat *formatter, NSString *value, UDateFormatSymbolType symbol, int index, UErrorCode &error) +{ + udat_setSymbols((UDateFormat *) formatter, (UDateFormatSymbolType) symbol, index, (UChar *) [value rawCharacters], [value length], &error); +} + +static void SetSymbolsFromNSArray(icu::DateFormat *formatter, NSArray *values, UDateFormatSymbolType symbol, int startIdx, UErrorCode &error) +{ + for ( int i = 0; i < [values count]; i ++ ) { + NSString *symbolStr = [values objectAtIndex: i]; + + udat_setSymbols((UDateFormat *) formatter, (UDateFormatSymbolType) symbol, i + startIdx, (UChar *) [symbolStr rawCharacters], [symbolStr length], &error); + } +} + +static std::map _icuProperties = { + { ICUPropertyMapper::lenient, ICUPropertyMapper(ICUPropertyMapper::lenient, + [](icu::DateFormat *formatter, ICUPropertyValue &value, UErrorCode &error) { + udat_setLenient((UDateFormat *) formatter, value._boolValue); + }, + [](icu::DateFormat *formatter, ICUPropertyValue &value, UErrorCode &error) { + value._boolValue = udat_isLenient((UDateFormat *) formatter); + }) + }, + + { ICUPropertyMapper::amSymbol, ICUPropertyMapper(ICUPropertyMapper::amSymbol, + [](icu::DateFormat *formatter, ICUPropertyValue &value, UErrorCode &error) { + SetSymbolFromNSString(formatter, (NSString *) value._objValue, (UDateFormatSymbolType) UDAT_AM_PMS, 0, error); + }, + [](icu::DateFormat *formatter, ICUPropertyValue &value, UErrorCode &error) { + value._objValue = NSStringFromSymbol(formatter, (UDateFormatSymbolType) UDAT_AM_PMS, 0, error); + }) + }, + + { ICUPropertyMapper::pmSymbol, ICUPropertyMapper(ICUPropertyMapper::pmSymbol, + [](icu::DateFormat *formatter, ICUPropertyValue &value, UErrorCode &error) { + SetSymbolFromNSString(formatter, (NSString *) value._objValue, (UDateFormatSymbolType) UDAT_AM_PMS, 1, error); + }, + [](icu::DateFormat *formatter, ICUPropertyValue &value, UErrorCode &error) { + value._objValue = NSStringFromSymbol(formatter, (UDateFormatSymbolType) UDAT_AM_PMS, 1, error); + }) + }, + + { ICUPropertyMapper::shortStandaloneWeekdaySymbols, ICUPropertyMapper(ICUPropertyMapper::shortStandaloneWeekdaySymbols, + [](icu::DateFormat *formatter, ICUPropertyValue &value, UErrorCode &error) { + SetSymbolsFromNSArray(formatter, (NSArray *) value._objValue, (UDateFormatSymbolType) UDAT_STANDALONE_SHORT_WEEKDAYS, 1, error); + }, + [](icu::DateFormat *formatter, ICUPropertyValue &value, UErrorCode &error) { + value._objValue = NSArrayFromSymbols(formatter, (UDateFormatSymbolType) UDAT_STANDALONE_SHORT_WEEKDAYS, 1, error); + }) + }, + + { ICUPropertyMapper::weekdaySymbols, ICUPropertyMapper(ICUPropertyMapper::weekdaySymbols, + [](icu::DateFormat *formatter, ICUPropertyValue &value, UErrorCode &error) { + SetSymbolsFromNSArray(formatter, (NSArray *) value._objValue, (UDateFormatSymbolType) UDAT_WEEKDAYS, 1, error); + }, + [](icu::DateFormat *formatter, ICUPropertyValue &value, UErrorCode &error) { + value._objValue = NSArrayFromSymbols(formatter, (UDateFormatSymbolType) UDAT_WEEKDAYS, 1, error); + }) + }, + + { ICUPropertyMapper::shortWeekdaySymbols, ICUPropertyMapper(ICUPropertyMapper::shortWeekdaySymbols, + [](icu::DateFormat *formatter, ICUPropertyValue &value, UErrorCode &error) { + SetSymbolsFromNSArray(formatter, (NSArray *) value._objValue, (UDateFormatSymbolType) UDAT_SHORT_WEEKDAYS, 1, error); + }, + [](icu::DateFormat *formatter, ICUPropertyValue &value, UErrorCode &error) { + value._objValue = NSArrayFromSymbols(formatter, (UDateFormatSymbolType) UDAT_SHORT_WEEKDAYS, 1, error); + }) + }, + + { ICUPropertyMapper::standaloneWeekdaySymbols, ICUPropertyMapper(ICUPropertyMapper::standaloneWeekdaySymbols, + [](icu::DateFormat *formatter, ICUPropertyValue &value, UErrorCode &error) { + SetSymbolsFromNSArray(formatter, (NSArray *) value._objValue, (UDateFormatSymbolType) UDAT_STANDALONE_WEEKDAYS, 1, error); + }, + [](icu::DateFormat *formatter, ICUPropertyValue &value, UErrorCode &error) { + value._objValue = NSArrayFromSymbols(formatter, (UDateFormatSymbolType) UDAT_STANDALONE_WEEKDAYS, 1, error); + }) + }, + + { ICUPropertyMapper::standaloneMonthSymbols, ICUPropertyMapper(ICUPropertyMapper::standaloneMonthSymbols, + [](icu::DateFormat *formatter, ICUPropertyValue &value, UErrorCode &error) { + SetSymbolsFromNSArray(formatter, (NSArray *) value._objValue, (UDateFormatSymbolType) UDAT_STANDALONE_MONTHS, 0, error); + }, + [](icu::DateFormat *formatter, ICUPropertyValue &value, UErrorCode &error) { + value._objValue = NSArrayFromSymbols(formatter, (UDateFormatSymbolType) UDAT_STANDALONE_MONTHS, 0, error); + }) + }, + + { ICUPropertyMapper::monthSymbols, ICUPropertyMapper(ICUPropertyMapper::monthSymbols, + [](icu::DateFormat *formatter, ICUPropertyValue &value, UErrorCode &error) { + SetSymbolsFromNSArray(formatter, (NSArray *) value._objValue, (UDateFormatSymbolType) UDAT_MONTHS, 0, error); + }, + [](icu::DateFormat *formatter, ICUPropertyValue &value, UErrorCode &error) { + value._objValue = NSArrayFromSymbols(formatter, (UDateFormatSymbolType) UDAT_MONTHS, 0, error); + }) + }, +}; + +@implementation NSDateFormatter { + NSDateFormatterStyle _dateStyle; + NSDateFormatterStyle _timeStyle; + idretaintype(NSString) _dateFormat; + BOOL _lenient, _lenientSet; + idretaintype(NSLocale) _locale; + idretaintype(NSTimeZone) _timeZone; + idretaintype(NSCalendar) _calendar; + + icu::DateFormat* _formatter; + BOOL _formatterNeedsRebuilding; + + std::map _valueOverrides; +} + +(NSString *) dateFormatFromTemplate: (NSString *)dateTemplate options:(NSUInteger)options locale:(NSLocale *)locale { + UErrorCode error = U_ZERO_ERROR; + icu::Locale *icuLocale = [locale _createICULocale]; + DateTimePatternGenerator *pg = DateTimePatternGenerator::createInstance(*icuLocale, error); + delete icuLocale; + UStringHolder strTemplate(dateTemplate); + + UnicodeString strSkeleton = pg->getSkeleton(strTemplate.string(), error); + if ( U_FAILURE(error) ) { + delete pg; + return nil; + } + + UnicodeString pattern = pg->getBestPattern(strSkeleton, error); + if ( U_FAILURE(error) ) { + delete pg; + return nil; + } + + NSString *ret = NSStringFromICU(pattern); + + delete pg; + + return ret; + } + + -(ICUPropertyValue) _getFormatterProperty: (ICUPropertyMapper::PropertyTypes) type + { + auto pos = _valueOverrides.find(type); + if ( pos != _valueOverrides.end() ) { + return pos->second; + } else { + ICUPropertyValue ret; + + UErrorCode status = U_ZERO_ERROR; + _icuProperties[type]._getProperty([self _getFormatter], ret, status); + + return ret; + } + } + + -(void) _setFormatterProperty: (ICUPropertyMapper::PropertyTypes) type withValue: (ICUPropertyValue) value + { + _valueOverrides[type] = value; + _formatterNeedsRebuilding = TRUE; + } + + -(icu::DateFormat*) _getFormatter + { + if ( !_formatter || _formatterNeedsRebuilding ) { + _formatterNeedsRebuilding = FALSE; + + if ( _formatter ) delete _formatter; + + UErrorCode status = U_ZERO_ERROR; + icu::Locale *icuLocale = [_locale _createICULocale]; + + if ( [_dateFormat length] > 0 ) { + UStringHolder fmtString(_dateFormat); + + _formatter = new SimpleDateFormat(fmtString.string(), *icuLocale, status); + } else { + _formatter = icu::DateFormat::createDateTimeInstance(convertFormatterStyle(_dateStyle), convertFormatterStyle(_timeStyle), *icuLocale); + } + + delete icuLocale; + + // Set calendar + icu::Calendar *calendar = [_calendar _createICUCalendar]; + _formatter->setCalendar(*calendar); + delete calendar; + + // Set all overridden properties + for ( auto &curProperty : _valueOverrides ) { + _icuProperties[curProperty.first]._setProperty(_formatter, curProperty.second, status); + } + + // Set timezone + icu::TimeZone *icuTimezone = [_timeZone _createICUTimeZone]; + _formatter->setTimeZone(*icuTimezone); + delete icuTimezone; + } + + return _formatter; + } + + -(instancetype) init { + return [self initWithDateFormat:@"" allowNaturalLanguage: NO]; + } + + -(instancetype) copyWithZone: (NSZone *)zone { + NSDateFormatter* copy = [super copyWithZone: zone]; + + copy->_dateStyle = _dateStyle; + copy->_timeStyle = _timeStyle; + copy->_dateFormat = _dateFormat; + copy->_locale = _locale; + copy->_timeZone = _timeZone; + copy->_valueOverrides = _valueOverrides; + + return copy; + } + + -(instancetype) initWithDateFormat: (NSString *)format allowNaturalLanguage: (BOOL)flag { + return [self initWithDateFormat:format allowNaturalLanguage:flag locale: [NSLocale currentLocale]]; + } + + -(instancetype) initWithDateFormat: (NSString *)format allowNaturalLanguage:(BOOL)flag locale:(NSLocale *)locale { + if ( flag == YES ) { + [NSException raiseWithLogging: @"NSDateFormatterException" format: @"allowNatrualLanguage = YES not supported"]; + } + + [super init]; + _formatter = 0; + _dateFormat.attach([format copy]); + _locale = locale; + + _timeZone = [NSTimeZone defaultTimeZone]; + _calendar = [NSCalendar currentCalendar]; + + return self; + } + + -(void) dealloc { + _dateFormat = nil; + _locale = nil; + _timeZone = nil; + + if ( _formatter ) delete _formatter; + + return [super dealloc]; + } + + -(void) setCalendar: (NSCalendar *)cal { + if ( _calendar == cal ) return; + + _calendar = cal; + _formatterNeedsRebuilding = TRUE; + } + + -(NSCalendar *) calendar + { + return _calendar; + } + + -(void) setTimeZone: (NSTimeZone *)zone { + if ( _timeZone == zone ) return; + + _timeZone = zone; + _formatterNeedsRebuilding = TRUE; + } + + -(NSTimeZone *) timeZone + { + return _timeZone; + } + + -(void) setLocale: (NSLocale *)locale { + if ( _locale == locale ) return; + + _locale = locale; + _formatterNeedsRebuilding = TRUE; + } + + -(NSLocale *) locale + { + return _locale; + } + + -(void) setLenient:(BOOL)lenient { + [self _setFormatterProperty: ICUPropertyMapper::lenient withValue: ICUPropertyValue(lenient)]; + } + + -(BOOL) lenient + { + return [self _getFormatterProperty: ICUPropertyMapper::lenient]._boolValue; + } + + -(void) setDateFormat: (NSString *)format { + if ( _dateFormat == format ) return; + + _dateFormat = format; + _formatterNeedsRebuilding = TRUE; + } + + -(NSString *) dateFormat + { + return _dateFormat; + } + + -(void) setDateStyle:(NSDateFormatterStyle)style { + if ( _dateStyle == style ) return; + _dateStyle = style; + _formatterNeedsRebuilding = TRUE; + } + + -(NSDateFormatterStyle) dateStyle + { + return _dateStyle; + } + + -(void) setTimeStyle:(NSDateFormatterStyle)style { + if ( _timeStyle == style ) return; + _timeStyle = style; + _formatterNeedsRebuilding = TRUE; + } + + -(NSDateFormatterStyle) timeStyle { + return _timeStyle; + } + + -(NSString *) stringFromDate:(NSDate *)date { + if ( date == nil ) return nil; + + UnicodeString str; + + [self _getFormatter]->format([date timeIntervalSince1970] * 1000.0, str); + + return NSStringFromICU(str); + } + + -(NSDate *) dateFromString:(NSString *)str { + UStringHolder uStr (str); + UErrorCode status = U_ZERO_ERROR; + UDate date = [self _getFormatter]->parse(uStr.string(), status); + + if ( !U_SUCCESS(status) ) return nil; + return [NSDate dateWithTimeIntervalSince1970:date / 1000.0]; + } + + -(BOOL) getObjectValue:(id *) outObj forString:(id)str errorDescription:(NSString **)err { + if ( err ) *err = nil; + + *outObj = [self dateFromString:str]; + return TRUE; + } + + -(NSString *) stringForObjectValue:(NSObject *)object { + if ( [object isKindOfClass: [NSDate class]] ) { + return [self stringFromDate: (NSDate *) object]; + } else { + return nil; + } + } + + -(void) setAMSymbol:(NSString *)symbol { + [self _setFormatterProperty: ICUPropertyMapper::amSymbol withValue: ICUPropertyValue(symbol)]; + } + + -(NSString *) AMSymbol { + return (NSString *) [self _getFormatterProperty: ICUPropertyMapper::amSymbol]._objValue; + } + + -(void) setPMSymbol:(NSString *)symbol { + [self _setFormatterProperty: ICUPropertyMapper::pmSymbol withValue: ICUPropertyValue(symbol)]; + } + + -(NSString *) PMSymbol { + return (NSString *) [self _getFormatterProperty: ICUPropertyMapper::pmSymbol]._objValue; + } + + -(void) setShortStandaloneWeekdaySymbols: (NSArray *) symbols { + [self _setFormatterProperty: ICUPropertyMapper::shortStandaloneWeekdaySymbols withValue: ICUPropertyValue(symbols)]; + } + + -(NSArray *) shortStandaloneWeekdaySymbols { + return (NSArray *) [self _getFormatterProperty: ICUPropertyMapper::shortStandaloneWeekdaySymbols]._objValue; + } + + -(void) setWeekdaySymbols: (NSArray *) symbols { + [self _setFormatterProperty: ICUPropertyMapper::weekdaySymbols withValue: ICUPropertyValue(symbols)]; + } + + -(NSArray *) weekdaySymbols { + return (NSArray *) [self _getFormatterProperty: ICUPropertyMapper::weekdaySymbols]._objValue; + } + + -(void) setShortWeekdaySymbols: (NSArray *) symbols { + [self _setFormatterProperty: ICUPropertyMapper::shortWeekdaySymbols withValue: ICUPropertyValue(symbols)]; + } + + -(NSArray *) shortWeekdaySymbols { + return (NSArray *) [self _getFormatterProperty: ICUPropertyMapper::shortWeekdaySymbols]._objValue; + } + + -(void) setStandaloneWeekdaySymbols: (NSArray *) symbols { + [self _setFormatterProperty: ICUPropertyMapper::standaloneWeekdaySymbols withValue: ICUPropertyValue(symbols)]; + } + + -(NSArray *) standaloneWeekdaySymbols { + return (NSArray *) [self _getFormatterProperty: ICUPropertyMapper::standaloneWeekdaySymbols]._objValue; + } + + -(void) setStandaloneMonthSymbols: (NSArray *) symbols { + [self _setFormatterProperty: ICUPropertyMapper::standaloneMonthSymbols withValue: ICUPropertyValue(symbols)]; + } + + -(NSArray *) standaloneMonthSymbols { + return (NSArray *) [self _getFormatterProperty: ICUPropertyMapper::standaloneMonthSymbols]._objValue; + } + + -(void) setMonthSymbols: (NSArray *) symbols { + [self _setFormatterProperty: ICUPropertyMapper::monthSymbols withValue: ICUPropertyValue(symbols)]; + } + + -(NSArray *) monthSymbols { + return (NSArray *) [self _getFormatterProperty: ICUPropertyMapper::monthSymbols]._objValue; + } +@end + diff --git a/Frameworks/Foundation/NSLocale.mm b/Frameworks/Foundation/NSLocale.mm new file mode 100644 index 0000000000..be6be2a8e7 --- /dev/null +++ b/Frameworks/Foundation/NSLocale.mm @@ -0,0 +1,105 @@ +//****************************************************************************** +// +// Copyright (c) 2015 Microsoft Corporation. All rights reserved. +// +// This code is licensed under the MIT License (MIT). +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +// THE SOFTWARE. +// +//****************************************************************************** + +#include "Starboard.h" + +#import +#include +#include +#include + +NSString * const NSLocaleCountryCode = @"NSLocaleCountryCode"; +NSString * const NSLocaleLanguageCode = @"NSLocaleLanguageCode"; +NSString * const NSLocaleVariantCode = @"NSLocaleVariantCode"; +NSString * const NSLocaleIdentifier = @"NSLocaleIdentifier"; + +NSString * const NSLocaleGroupingSeparator = @"NSLocaleGroupingSeparator"; +NSString * const NSLocaleDecimalSeparator = @"NSLocaleDecimalSeparator"; +NSString * const NSLocaleCalendar = @"NSLocaleCalendar"; +NSString * const NSLocaleCurrencyCode = @"NSLocaleCurrencyCode"; +NSString * const NSLocaleCurrencySymbol = @"NSLocaleCurrencySymbol"; +NSString * const NSLocaleUsesMetricSystem = @"NSLocaleUsesMetricSystem"; +NSString * const NSLocaleMeasurementSystem = @"NSLocaleMeasurementSystem"; + +NSString * const NSLocaleScriptCode = @"NSLocaleScriptCode"; +NSString * const NSLocaleExemplarCharacterSet = @"NSLocaleExemplarCharacterSet"; +NSString * const NSLocaleCollationIdentifier = @"NSLocaleCollationIdentifier"; + +NSString * const NSCurrentLocaleDidChangeNotification = @"NSCurrentLocaleDidChangeNotification"; + +static NSLocale *_currentLocale; + +@implementation NSLocale { + icu::Locale _locale; +} + + -(icu::Locale *) _createICULocale + { + return _locale.clone(); + } + + -(instancetype) init + { + _locale = icu::Locale(); + + return self; + } + + -(instancetype) initWithLocaleIdentifier: (NSString *) identifier + { + _locale = icu::Locale::createFromName([identifier UTF8String]); + + return self; + } + + +(instancetype) localeWithLocaleIdentifier: (NSString *) identifier + { + return [[[self alloc] initWithLocaleIdentifier: identifier] autorelease]; + } + + -(NSString *) localeIdentifier + { + return [NSString stringWithUTF8String: _locale.getName()]; + } + + -(NSString *)displayNameForKey: (id) key value: (id) value + { + if ( [NSLocaleIdentifier isEqualToString: key] ) { + icu::Locale displayLocale = icu::Locale::createFromName([value UTF8String]); + + UnicodeString retStr; + displayLocale.getDisplayName(_locale, retStr); + + return NSStringFromICU(retStr); + } else { + [NSException raiseWithLogging: @"NSLocaleException" format: @"displayNameForKey: Unknown key %@", key]; + return nil; + } + } + + +(void) initialize + { + if ( self == [NSLocale class] ) + { + _currentLocale = [self new]; + } + } + + +(instancetype) currentLocale + { + return _currentLocale; + } +@end diff --git a/Frameworks/Foundation/NSNumberFormatter.mm b/Frameworks/Foundation/NSNumberFormatter.mm index 9588854b2c..aec2b07944 100644 --- a/Frameworks/Foundation/NSNumberFormatter.mm +++ b/Frameworks/Foundation/NSNumberFormatter.mm @@ -22,11 +22,7 @@ static NSNumberFormatterBehavior _defaultFormatterBehavior = NSNumberFormatterBehavior10_4; -NSString* const NSLocaleDecimalSeparator = @"NSLocaleDecimalSeparator"; -NSString* const NSLocaleGroupingSeparator = @"NSLocaleGroupingSeparator"; - #if 0 -id NSLocaleDecimalSeparator, NSLocaleGroupingSeparator; id kCFNumberNaN; id kCFNumberPositiveInfinity; id kCFNumberNegativeInfinity; diff --git a/Frameworks/Foundation/NSTimeZone.mm b/Frameworks/Foundation/NSTimeZone.mm index 8243de6312..f8454e87b6 100644 --- a/Frameworks/Foundation/NSTimeZone.mm +++ b/Frameworks/Foundation/NSTimeZone.mm @@ -20,22 +20,57 @@ #include "Foundation/NSArray.h" #include "Etc.h" #include "Foundation/NSTimeZone.h" - -#define U_STATIC_IMPLEMENTATION 1 +#include "NSTimeZoneInternal.h" #include +#include + +static NSTimeZone *_defaultTimeZone; +static dispatch_once_t _systemTimeZoneInit; +static NSTimeZone *_systemTimeZone; @implementation NSTimeZone { - icu_48::TimeZone* _icuTZ; + icu::TimeZone* _icuTZ; } + +(void) _setTimeZoneToSystemSettings: (icu::TimeZone *) tz + { + /* Implement me! */ + } + + +(NSTimeZone *) _getSystemTZ + { + dispatch_once(&_systemTimeZoneInit, ^{ + _systemTimeZone = [self alloc]; + _systemTimeZone->_icuTZ = icu_48::TimeZone::createDefault(); + [self _setTimeZoneToSystemSettings: _systemTimeZone->_icuTZ]; + }); + + return _systemTimeZone; + } + +(instancetype) systemTimeZone { - NSTimeZone* ret = [self alloc]; - ret->_icuTZ = icu_48::TimeZone::createDefault(); - return [ret autorelease]; + return [self _getSystemTZ]; + } + + +(void) resetSystemTimeZone { + [self _setTimeZoneToSystemSettings: [self _getSystemTZ]->_icuTZ]; } +(instancetype) defaultTimeZone { - return [self systemTimeZone]; + NSTimeZone *ret; + + if ( _defaultTimeZone != nil ) { + ret = _defaultTimeZone; + } else { + ret = [self systemTimeZone]; + } + return [[ret copy] autorelease]; + } + + +(void) setDefaultTimeZone: (NSTimeZone *) zone { + zone = [zone retain]; + [_defaultTimeZone release]; + _defaultTimeZone = zone; } +(NSArray*) knownTimeZoneNames { @@ -43,8 +78,9 @@ +(NSArray*) knownTimeZoneNames { return [NSArray arrayWithObject:@"America/Los_Angeles"]; } - -(void) _getICUTimezone:(icu_48::TimeZone**)tz { - *tz = _icuTZ; + -(icu::TimeZone *) _createICUTimeZone + { + return _icuTZ->clone(); } +(instancetype) timeZoneForSecondsFromGMT:(NSInteger)seconds { @@ -55,7 +91,10 @@ +(instancetype) timeZoneForSecondsFromGMT:(NSInteger)seconds { } +(instancetype) localTimeZone { - return [self timeZoneWithName:@"America/Toronto"]; + if ( _defaultTimeZone != nil ) { + return [[_defaultTimeZone retain] autorelease]; + } + return [self systemTimeZone]; } +(instancetype) _gmtTimeZone { @@ -114,12 +153,6 @@ -(instancetype) copyWithZone:(NSZone*)zone { return [self retain]; } - +(void) resetSystemTimeZone { - } - - +(void) setDefaultTimeZone:(NSTimeZone*)zone { - } - -(BOOL) isDaylightSavingTimeForDate: (NSDate *) date { UErrorCode status = U_ZERO_ERROR; diff --git a/Frameworks/include/NSCalendarInternal.h b/Frameworks/include/NSCalendarInternal.h new file mode 100644 index 0000000000..a87e378b0f --- /dev/null +++ b/Frameworks/include/NSCalendarInternal.h @@ -0,0 +1,23 @@ +//****************************************************************************** +// +// Copyright (c) 2015 Microsoft Corporation. All rights reserved. +// +// This code is licensed under the MIT License (MIT). +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +// THE SOFTWARE. +// +//****************************************************************************** + +#pragma once + +#include + +@interface NSCalendar(Internal) + -(icu::Calendar *) _createICUCalendar; +@end \ No newline at end of file diff --git a/Frameworks/include/NSLocaleInternal.h b/Frameworks/include/NSLocaleInternal.h new file mode 100644 index 0000000000..1bd7be86fb --- /dev/null +++ b/Frameworks/include/NSLocaleInternal.h @@ -0,0 +1,23 @@ +//****************************************************************************** +// +// Copyright (c) 2015 Microsoft Corporation. All rights reserved. +// +// This code is licensed under the MIT License (MIT). +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +// THE SOFTWARE. +// +//****************************************************************************** + +#pragma once + +#import + +@interface NSLocale(Internal) + -(icu::Locale *) _createICULocale; +@end \ No newline at end of file diff --git a/Frameworks/include/NSTimeZoneInternal.h b/Frameworks/include/NSTimeZoneInternal.h new file mode 100644 index 0000000000..01c097b2ad --- /dev/null +++ b/Frameworks/include/NSTimeZoneInternal.h @@ -0,0 +1,23 @@ +//****************************************************************************** +// +// Copyright (c) 2015 Microsoft Corporation. All rights reserved. +// +// This code is licensed under the MIT License (MIT). +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +// THE SOFTWARE. +// +//****************************************************************************** + +#pragma once + +#include + +@interface NSTimeZone(Internal) + -(icu::TimeZone *) _createICUTimeZone; +@end \ No newline at end of file diff --git a/build/Foundation/Foundation.Shared/Foundation.Shared.vcxitems b/build/Foundation/Foundation.Shared/Foundation.Shared.vcxitems index 308750279d..e75908b935 100644 --- a/build/Foundation/Foundation.Shared/Foundation.Shared.vcxitems +++ b/build/Foundation/Foundation.Shared/Foundation.Shared.vcxitems @@ -110,6 +110,7 @@ + diff --git a/build/Foundation/Foundation.Shared/Foundation.Shared.vcxitems.filters b/build/Foundation/Foundation.Shared/Foundation.Shared.vcxitems.filters index 5c9e137e22..ad0fe162a6 100644 --- a/build/Foundation/Foundation.Shared/Foundation.Shared.vcxitems.filters +++ b/build/Foundation/Foundation.Shared/Foundation.Shared.vcxitems.filters @@ -91,6 +91,7 @@ + diff --git a/build/Foundation/Foundation.Shared/Foundation.def b/build/Foundation/Foundation.Shared/Foundation.def index d2734df421..90d2645c9d 100644 --- a/build/Foundation/Foundation.Shared/Foundation.def +++ b/build/Foundation/Foundation.Shared/Foundation.def @@ -130,3 +130,5 @@ LIBRARY Foundation __objc_class_name_NSKeyedArchiver CONSTANT _OBJC_CLASS_NSKeyedUnarchiver DATA __objc_class_name_NSKeyedUnarchiver CONSTANT + _OBJC_CLASS_NSLocale DATA + __objc_class_name_NSLocale CONSTANT diff --git a/deps/prebuilt/include/icu/unicode/datefmt.h b/deps/prebuilt/include/icu/unicode/datefmt.h new file mode 100644 index 0000000000..c79dec8912 --- /dev/null +++ b/deps/prebuilt/include/icu/unicode/datefmt.h @@ -0,0 +1,751 @@ +/* + ******************************************************************************** + * Copyright (C) 1997-2011, International Business Machines + * Corporation and others. All Rights Reserved. + ******************************************************************************** + * + * File DATEFMT.H + * + * Modification History: + * + * Date Name Description + * 02/19/97 aliu Converted from java. + * 04/01/97 aliu Added support for centuries. + * 07/23/98 stephen JDK 1.2 sync + * 11/15/99 weiv Added support for week of year/day of week formatting + ******************************************************************************** + */ + +#ifndef DATEFMT_H +#define DATEFMT_H + +#include "unicode/utypes.h" + +#if !UCONFIG_NO_FORMATTING + +#include "unicode/udat.h" +#include "unicode/calendar.h" +#include "unicode/numfmt.h" +#include "unicode/format.h" +#include "unicode/locid.h" + +/** + * \file + * \brief C++ API: Abstract class for converting dates. + */ + +U_NAMESPACE_BEGIN + +class TimeZone; +class DateTimePatternGenerator; + +/** + * DateFormat is an abstract class for a family of classes that convert dates and + * times from their internal representations to textual form and back again in a + * language-independent manner. Converting from the internal representation (milliseconds + * since midnight, January 1, 1970) to text is known as "formatting," and converting + * from text to millis is known as "parsing." We currently define only one concrete + * subclass of DateFormat: SimpleDateFormat, which can handle pretty much all normal + * date formatting and parsing actions. + *

+ * DateFormat helps you to format and parse dates for any locale. Your code can + * be completely independent of the locale conventions for months, days of the + * week, or even the calendar format: lunar vs. solar. + *

+ * To format a date for the current Locale, use one of the static factory + * methods: + *

+ * \code
+ *      DateFormat* dfmt = DateFormat::createDateInstance();
+ *      UDate myDate = Calendar::getNow();
+ *      UnicodeString myString;
+ *      myString = dfmt->format( myDate, myString );
+ * \endcode
+ * 
+ * If you are formatting multiple numbers, it is more efficient to get the + * format and use it multiple times so that the system doesn't have to fetch the + * information about the local language and country conventions multiple times. + *
+ * \code
+ *      DateFormat* df = DateFormat::createDateInstance();
+ *      UnicodeString myString;
+ *      UDate myDateArr[] = { 0.0, 100000000.0, 2000000000.0 }; // test values
+ *      for (int32_t i = 0; i < 3; ++i) {
+ *          myString.remove();
+ *          cout << df->format( myDateArr[i], myString ) << endl;
+ *      }
+ * \endcode
+ * 
+ * To get specific fields of a date, you can use UFieldPosition to + * get specific fields. + *
+ * \code
+ *      DateFormat* dfmt = DateFormat::createDateInstance();
+ *      FieldPosition pos(DateFormat::YEAR_FIELD);
+ *      UnicodeString myString;
+ *      myString = dfmt->format( myDate, myString );
+ *      cout << myString << endl;
+ *      cout << pos.getBeginIndex() << "," << pos. getEndIndex() << endl;
+ * \endcode
+ * 
+ * To format a date for a different Locale, specify it in the call to + * createDateInstance(). + *
+ * \code
+ *       DateFormat* df =
+ *           DateFormat::createDateInstance( DateFormat::SHORT, Locale::getFrance());
+ * \endcode
+ * 
+ * You can use a DateFormat to parse also. + *
+ * \code
+ *       UErrorCode status = U_ZERO_ERROR;
+ *       UDate myDate = df->parse(myString, status);
+ * \endcode
+ * 
+ * Use createDateInstance() to produce the normal date format for that country. + * There are other static factory methods available. Use createTimeInstance() + * to produce the normal time format for that country. Use createDateTimeInstance() + * to produce a DateFormat that formats both date and time. You can pass in + * different options to these factory methods to control the length of the + * result; from SHORT to MEDIUM to LONG to FULL. The exact result depends on the + * locale, but generally: + *
    + *
  • SHORT is completely numeric, such as 12/13/52 or 3:30pm + *
  • MEDIUM is longer, such as Jan 12, 1952 + *
  • LONG is longer, such as January 12, 1952 or 3:30:32pm + *
  • FULL is pretty completely specified, such as + * Tuesday, April 12, 1952 AD or 3:30:42pm PST. + *
+ * You can also set the time zone on the format if you wish. If you want even + * more control over the format or parsing, (or want to give your users more + * control), you can try casting the DateFormat you get from the factory methods + * to a SimpleDateFormat. This will work for the majority of countries; just + * remember to chck getDynamicClassID() before carrying out the cast. + *

+ * You can also use forms of the parse and format methods with ParsePosition and + * FieldPosition to allow you to + *

    + *
  • Progressively parse through pieces of a string. + *
  • Align any particular field, or find out where it is for selection + * on the screen. + *
+ * + *

User subclasses are not supported. While clients may write + * subclasses, such code will not necessarily work and will not be + * guaranteed to work stably from release to release. + */ +class U_I18N_API DateFormat : public Format { +public: + + /** + * Constants for various style patterns. These reflect the order of items in + * the DateTimePatterns resource. There are 4 time patterns, 4 date patterns, + * the default date-time pattern, and 4 date-time patterns. Each block of 4 values + * in the resource occurs in the order full, long, medium, short. + * @stable ICU 2.4 + */ + enum EStyle + { + kNone = -1, + + kFull = 0, + kLong = 1, + kMedium = 2, + kShort = 3, + + kDateOffset = kShort + 1, + // kFull + kDateOffset = 4 + // kLong + kDateOffset = 5 + // kMedium + kDateOffset = 6 + // kShort + kDateOffset = 7 + + kDateTime = 8, + // Default DateTime + + kDateTimeOffset = kDateTime + 1, + // kFull + kDateTimeOffset = 9 + // kLong + kDateTimeOffset = 10 + // kMedium + kDateTimeOffset = 11 + // kShort + kDateTimeOffset = 12 + + // relative dates + kRelative = (1 << 7), + + kFullRelative = (kFull | kRelative), + + kLongRelative = kLong | kRelative, + + kMediumRelative = kMedium | kRelative, + + kShortRelative = kShort | kRelative, + + + kDefault = kMedium, + + + + /** + * These constants are provided for backwards compatibility only. + * Please use the C++ style constants defined above. + */ + FULL = kFull, + LONG = kLong, + MEDIUM = kMedium, + SHORT = kShort, + DEFAULT = kDefault, + DATE_OFFSET = kDateOffset, + NONE = kNone, + DATE_TIME = kDateTime + }; + + /** + * Destructor. + * @stable ICU 2.0 + */ + virtual ~DateFormat(); + + /** + * Equality operator. Returns true if the two formats have the same behavior. + * @stable ICU 2.0 + */ + virtual UBool operator==(const Format&) const; + + + using Format::format; + + /** + * Format an object to produce a string. This method handles Formattable + * objects with a UDate type. If a the Formattable object type is not a Date, + * then it returns a failing UErrorCode. + * + * @param obj The object to format. Must be a Date. + * @param appendTo Output parameter to receive result. + * Result is appended to existing contents. + * @param pos On input: an alignment field, if desired. + * On output: the offsets of the alignment field. + * @param status Output param filled with success/failure status. + * @return Reference to 'appendTo' parameter. + * @stable ICU 2.0 + */ + virtual UnicodeString& format(const Formattable& obj, + UnicodeString& appendTo, + FieldPosition& pos, + UErrorCode& status) const; + + /** + * Format an object to produce a string. This method handles Formattable + * objects with a UDate type. If a the Formattable object type is not a Date, + * then it returns a failing UErrorCode. + * + * @param obj The object to format. Must be a Date. + * @param appendTo Output parameter to receive result. + * Result is appended to existing contents. + * @param posIter On return, can be used to iterate over positions + * of fields generated by this format call. Field values + * are defined in UDateFormatField. Can be NULL. + * @param status Output param filled with success/failure status. + * @return Reference to 'appendTo' parameter. + * @stable ICU 4.4 + */ + virtual UnicodeString& format(const Formattable& obj, + UnicodeString& appendTo, + FieldPositionIterator* posIter, + UErrorCode& status) const; + /** + * Formats a date into a date/time string. This is an abstract method which + * concrete subclasses must implement. + *

+ * On input, the FieldPosition parameter may have its "field" member filled with + * an enum value specifying a field. On output, the FieldPosition will be filled + * in with the text offsets for that field. + *

For example, given a time text + * "1996.07.10 AD at 15:08:56 PDT", if the given fieldPosition.field is + * UDAT_YEAR_FIELD, the offsets fieldPosition.beginIndex and + * statfieldPositionus.getEndIndex will be set to 0 and 4, respectively. + *

Notice + * that if the same time field appears more than once in a pattern, the status will + * be set for the first occurence of that time field. For instance, + * formatting a UDate to the time string "1 PM PDT (Pacific Daylight Time)" + * using the pattern "h a z (zzzz)" and the alignment field + * DateFormat::TIMEZONE_FIELD, the offsets fieldPosition.beginIndex and + * fieldPosition.getEndIndex will be set to 5 and 8, respectively, for the first + * occurence of the timezone pattern character 'z'. + * + * @param cal Calendar set to the date and time to be formatted + * into a date/time string. When the calendar type is + * different from the internal calendar held by this + * DateFormat instance, the date and the time zone will + * be inherited from the input calendar, but other calendar + * field values will be calculated by the internal calendar. + * @param appendTo Output parameter to receive result. + * Result is appended to existing contents. + * @param fieldPosition On input: an alignment field, if desired (see examples above) + * On output: the offsets of the alignment field (see examples above) + * @return Reference to 'appendTo' parameter. + * @stable ICU 2.1 + */ + virtual UnicodeString& format( Calendar& cal, + UnicodeString& appendTo, + FieldPosition& fieldPosition) const = 0; + + /** + * Formats a date into a date/time string. Subclasses should implement this method. + * + * @param cal Calendar set to the date and time to be formatted + * into a date/time string. When the calendar type is + * different from the internal calendar held by this + * DateFormat instance, the date and the time zone will + * be inherited from the input calendar, but other calendar + * field values will be calculated by the internal calendar. + * @param appendTo Output parameter to receive result. + * Result is appended to existing contents. + * @param posIter On return, can be used to iterate over positions + * of fields generated by this format call. Field values + * are defined in UDateFormatField. Can be NULL. + * @param status error status. + * @return Reference to 'appendTo' parameter. + * @stable ICU 4.4 + */ + virtual UnicodeString& format(Calendar& cal, + UnicodeString& appendTo, + FieldPositionIterator* posIter, + UErrorCode& status) const; + /** + * Formats a UDate into a date/time string. + *

+ * On input, the FieldPosition parameter may have its "field" member filled with + * an enum value specifying a field. On output, the FieldPosition will be filled + * in with the text offsets for that field. + *

For example, given a time text + * "1996.07.10 AD at 15:08:56 PDT", if the given fieldPosition.field is + * UDAT_YEAR_FIELD, the offsets fieldPosition.beginIndex and + * statfieldPositionus.getEndIndex will be set to 0 and 4, respectively. + *

Notice + * that if the same time field appears more than once in a pattern, the status will + * be set for the first occurence of that time field. For instance, + * formatting a UDate to the time string "1 PM PDT (Pacific Daylight Time)" + * using the pattern "h a z (zzzz)" and the alignment field + * DateFormat::TIMEZONE_FIELD, the offsets fieldPosition.beginIndex and + * fieldPosition.getEndIndex will be set to 5 and 8, respectively, for the first + * occurence of the timezone pattern character 'z'. + * + * @param date UDate to be formatted into a date/time string. + * @param appendTo Output parameter to receive result. + * Result is appended to existing contents. + * @param fieldPosition On input: an alignment field, if desired (see examples above) + * On output: the offsets of the alignment field (see examples above) + * @return Reference to 'appendTo' parameter. + * @stable ICU 2.0 + */ + UnicodeString& format( UDate date, + UnicodeString& appendTo, + FieldPosition& fieldPosition) const; + + /** + * Formats a UDate into a date/time string. + * + * @param date UDate to be formatted into a date/time string. + * @param appendTo Output parameter to receive result. + * Result is appended to existing contents. + * @param posIter On return, can be used to iterate over positions + * of fields generated by this format call. Field values + * are defined in UDateFormatField. Can be NULL. + * @param status error status. + * @return Reference to 'appendTo' parameter. + * @stable ICU 4.4 + */ + UnicodeString& format(UDate date, + UnicodeString& appendTo, + FieldPositionIterator* posIter, + UErrorCode& status) const; + /** + * Formats a UDate into a date/time string. If there is a problem, you won't + * know, using this method. Use the overloaded format() method which takes a + * FieldPosition& to detect formatting problems. + * + * @param date The UDate value to be formatted into a string. + * @param appendTo Output parameter to receive result. + * Result is appended to existing contents. + * @return Reference to 'appendTo' parameter. + * @stable ICU 2.0 + */ + UnicodeString& format(UDate date, UnicodeString& appendTo) const; + + /** + * Redeclared Format method. + * + * @param obj The object to be formatted into a string. + * @param appendTo Output parameter to receive result. + * Result is appended to existing contents. + * @param status Output param filled with success/failure status. + * @return Reference to 'appendTo' parameter. + * @stable ICU 2.0 + */ + UnicodeString& format(const Formattable& obj, + UnicodeString& appendTo, + UErrorCode& status) const; + + /** + * Parse a date/time string. + * + * @param text The string to be parsed into a UDate value. + * @param status Output param to be set to success/failure code. If + * 'text' cannot be parsed, it will be set to a failure + * code. + * @result The parsed UDate value, if successful. + * @stable ICU 2.0 + */ + virtual UDate parse( const UnicodeString& text, + UErrorCode& status) const; + + /** + * Parse a date/time string beginning at the given parse position. For + * example, a time text "07/10/96 4:5 PM, PDT" will be parsed into a Date + * that is equivalent to Date(837039928046). + *

+ * By default, parsing is lenient: If the input is not in the form used by + * this object's format method but can still be parsed as a date, then the + * parse succeeds. Clients may insist on strict adherence to the format by + * calling setLenient(false). + * + * @see DateFormat::setLenient(boolean) + * + * @param text The date/time string to be parsed + * @param cal a Calendar set to the date and time to be formatted + * into a date/time string. When the calendar type + * is different from the internal calendar held by this + * DateFormat instance, calendar field values will be + * parsed based on the internal calendar, then the result + * (time in milliseconds and time zone) will be set in + * this calendar. + * @param pos On input, the position at which to start parsing; on + * output, the position at which parsing terminated, or the + * start position if the parse failed. + * @return A valid UDate if the input could be parsed. + * @stable ICU 2.1 + */ + virtual void parse( const UnicodeString& text, + Calendar& cal, + ParsePosition& pos) const = 0; + + /** + * Parse a date/time string beginning at the given parse position. For + * example, a time text "07/10/96 4:5 PM, PDT" will be parsed into a Date + * that is equivalent to Date(837039928046). + *

+ * By default, parsing is lenient: If the input is not in the form used by + * this object's format method but can still be parsed as a date, then the + * parse succeeds. Clients may insist on strict adherence to the format by + * calling setLenient(false). + * + * @see DateFormat::setLenient(boolean) + * + * @param text The date/time string to be parsed + * @param pos On input, the position at which to start parsing; on + * output, the position at which parsing terminated, or the + * start position if the parse failed. + * @return A valid UDate if the input could be parsed. + * @stable ICU 2.0 + */ + UDate parse( const UnicodeString& text, + ParsePosition& pos) const; + + /** + * Parse a string to produce an object. This methods handles parsing of + * date/time strings into Formattable objects with UDate types. + *

+ * Before calling, set parse_pos.index to the offset you want to start + * parsing at in the source. After calling, parse_pos.index is the end of + * the text you parsed. If error occurs, index is unchanged. + *

+ * When parsing, leading whitespace is discarded (with a successful parse), + * while trailing whitespace is left as is. + *

+ * See Format::parseObject() for more. + * + * @param source The string to be parsed into an object. + * @param result Formattable to be set to the parse result. + * If parse fails, return contents are undefined. + * @param parse_pos The position to start parsing at. Upon return + * this param is set to the position after the + * last character successfully parsed. If the + * source is not parsed successfully, this param + * will remain unchanged. + * @return A newly created Formattable* object, or NULL + * on failure. The caller owns this and should + * delete it when done. + * @stable ICU 2.0 + */ + virtual void parseObject(const UnicodeString& source, + Formattable& result, + ParsePosition& parse_pos) const; + + /** + * Create a default date/time formatter that uses the SHORT style for both + * the date and the time. + * + * @return A date/time formatter which the caller owns. + * @stable ICU 2.0 + */ + static DateFormat* U_EXPORT2 createInstance(void); + + /** + * Creates a time formatter with the given formatting style for the given + * locale. + * + * @param style The given formatting style. For example, + * SHORT for "h:mm a" in the US locale. Relative + * time styles are not currently supported. + * @param aLocale The given locale. + * @return A time formatter which the caller owns. + * @stable ICU 2.0 + */ + static DateFormat* U_EXPORT2 createTimeInstance(EStyle style = kDefault, + const Locale& aLocale = Locale::getDefault()); + + /** + * Creates a date formatter with the given formatting style for the given + * const locale. + * + * @param style The given formatting style. For example, + * SHORT for "M/d/yy" in the US locale. + * @param aLocale The given locale. + * @return A date formatter which the caller owns. + * @stable ICU 2.0 + */ + static DateFormat* U_EXPORT2 createDateInstance(EStyle style = kDefault, + const Locale& aLocale = Locale::getDefault()); + + /** + * Creates a date/time formatter with the given formatting styles for the + * given locale. + * + * @param dateStyle The given formatting style for the date portion of the result. + * For example, SHORT for "M/d/yy" in the US locale. + * @param timeStyle The given formatting style for the time portion of the result. + * For example, SHORT for "h:mm a" in the US locale. Relative + * time styles are not currently supported. + * @param aLocale The given locale. + * @return A date/time formatter which the caller owns. + * @stable ICU 2.0 + */ + static DateFormat* U_EXPORT2 createDateTimeInstance(EStyle dateStyle = kDefault, + EStyle timeStyle = kDefault, + const Locale& aLocale = Locale::getDefault()); + + /** + * Gets the set of locales for which DateFormats are installed. + * @param count Filled in with the number of locales in the list that is returned. + * @return the set of locales for which DateFormats are installed. The caller + * does NOT own this list and must not delete it. + * @stable ICU 2.0 + */ + static const Locale* U_EXPORT2 getAvailableLocales(int32_t& count); + + /** + * Returns true if the formatter is set for lenient parsing. + * @stable ICU 2.0 + */ + virtual UBool isLenient(void) const; + + /** + * Specify whether or not date/time parsing is to be lenient. With lenient + * parsing, the parser may use heuristics to interpret inputs that do not + * precisely match this object's format. With strict parsing, inputs must + * match this object's format. + * + * @param lenient True specifies date/time interpretation to be lenient. + * @see Calendar::setLenient + * @stable ICU 2.0 + */ + virtual void setLenient(UBool lenient); + + /** + * Gets the calendar associated with this date/time formatter. + * @return the calendar associated with this date/time formatter. + * @stable ICU 2.0 + */ + virtual const Calendar* getCalendar(void) const; + + /** + * Set the calendar to be used by this date format. Initially, the default + * calendar for the specified or default locale is used. The caller should + * not delete the Calendar object after it is adopted by this call. + * Adopting a new calendar will change to the default symbols. + * + * @param calendarToAdopt Calendar object to be adopted. + * @stable ICU 2.0 + */ + virtual void adoptCalendar(Calendar* calendarToAdopt); + + /** + * Set the calendar to be used by this date format. Initially, the default + * calendar for the specified or default locale is used. + * + * @param newCalendar Calendar object to be set. + * @stable ICU 2.0 + */ + virtual void setCalendar(const Calendar& newCalendar); + + + /** + * Gets the number formatter which this date/time formatter uses to format + * and parse the numeric portions of the pattern. + * @return the number formatter which this date/time formatter uses. + * @stable ICU 2.0 + */ + virtual const NumberFormat* getNumberFormat(void) const; + + /** + * Allows you to set the number formatter. The caller should + * not delete the NumberFormat object after it is adopted by this call. + * @param formatToAdopt NumberFormat object to be adopted. + * @stable ICU 2.0 + */ + virtual void adoptNumberFormat(NumberFormat* formatToAdopt); + + /** + * Allows you to set the number formatter. + * @param newNumberFormat NumberFormat object to be set. + * @stable ICU 2.0 + */ + virtual void setNumberFormat(const NumberFormat& newNumberFormat); + + /** + * Returns a reference to the TimeZone used by this DateFormat's calendar. + * @return the time zone associated with the calendar of DateFormat. + * @stable ICU 2.0 + */ + virtual const TimeZone& getTimeZone(void) const; + + /** + * Sets the time zone for the calendar of this DateFormat object. The caller + * no longer owns the TimeZone object and should not delete it after this call. + * @param zoneToAdopt the TimeZone to be adopted. + * @stable ICU 2.0 + */ + virtual void adoptTimeZone(TimeZone* zoneToAdopt); + + /** + * Sets the time zone for the calendar of this DateFormat object. + * @param zone the new time zone. + * @stable ICU 2.0 + */ + virtual void setTimeZone(const TimeZone& zone); + +protected: + /** + * Default constructor. Creates a DateFormat with no Calendar or NumberFormat + * associated with it. This constructor depends on the subclasses to fill in + * the calendar and numberFormat fields. + * @stable ICU 2.0 + */ + DateFormat(); + + /** + * Copy constructor. + * @stable ICU 2.0 + */ + DateFormat(const DateFormat&); + + /** + * Default assignment operator. + * @stable ICU 2.0 + */ + DateFormat& operator=(const DateFormat&); + + /** + * The calendar that DateFormat uses to produce the time field values needed + * to implement date/time formatting. Subclasses should generally initialize + * this to the default calendar for the locale associated with this DateFormat. + * @stable ICU 2.4 + */ + Calendar* fCalendar; + + /** + * The number formatter that DateFormat uses to format numbers in dates and + * times. Subclasses should generally initialize this to the default number + * format for the locale associated with this DateFormat. + * @stable ICU 2.4 + */ + NumberFormat* fNumberFormat; + +private: + /** + * Gets the date/time formatter with the given formatting styles for the + * given locale. + * @param dateStyle the given date formatting style. + * @param timeStyle the given time formatting style. + * @param inLocale the given locale. + * @return a date/time formatter, or 0 on failure. + */ + static DateFormat* U_EXPORT2 create(EStyle timeStyle, EStyle dateStyle, const Locale& inLocale); + +public: + /** + * Field selector for FieldPosition for DateFormat fields. + * @obsolete ICU 3.4 use UDateFormatField instead, since this API will be + * removed in that release + */ + enum EField + { + // Obsolete; use UDateFormatField instead + kEraField = UDAT_ERA_FIELD, + kYearField = UDAT_YEAR_FIELD, + kMonthField = UDAT_MONTH_FIELD, + kDateField = UDAT_DATE_FIELD, + kHourOfDay1Field = UDAT_HOUR_OF_DAY1_FIELD, + kHourOfDay0Field = UDAT_HOUR_OF_DAY0_FIELD, + kMinuteField = UDAT_MINUTE_FIELD, + kSecondField = UDAT_SECOND_FIELD, + kMillisecondField = UDAT_FRACTIONAL_SECOND_FIELD, + kDayOfWeekField = UDAT_DAY_OF_WEEK_FIELD, + kDayOfYearField = UDAT_DAY_OF_YEAR_FIELD, + kDayOfWeekInMonthField = UDAT_DAY_OF_WEEK_IN_MONTH_FIELD, + kWeekOfYearField = UDAT_WEEK_OF_YEAR_FIELD, + kWeekOfMonthField = UDAT_WEEK_OF_MONTH_FIELD, + kAmPmField = UDAT_AM_PM_FIELD, + kHour1Field = UDAT_HOUR1_FIELD, + kHour0Field = UDAT_HOUR0_FIELD, + kTimezoneField = UDAT_TIMEZONE_FIELD, + kYearWOYField = UDAT_YEAR_WOY_FIELD, + kDOWLocalField = UDAT_DOW_LOCAL_FIELD, + kExtendedYearField = UDAT_EXTENDED_YEAR_FIELD, + kJulianDayField = UDAT_JULIAN_DAY_FIELD, + kMillisecondsInDayField = UDAT_MILLISECONDS_IN_DAY_FIELD, + + // Obsolete; use UDateFormatField instead + ERA_FIELD = UDAT_ERA_FIELD, + YEAR_FIELD = UDAT_YEAR_FIELD, + MONTH_FIELD = UDAT_MONTH_FIELD, + DATE_FIELD = UDAT_DATE_FIELD, + HOUR_OF_DAY1_FIELD = UDAT_HOUR_OF_DAY1_FIELD, + HOUR_OF_DAY0_FIELD = UDAT_HOUR_OF_DAY0_FIELD, + MINUTE_FIELD = UDAT_MINUTE_FIELD, + SECOND_FIELD = UDAT_SECOND_FIELD, + MILLISECOND_FIELD = UDAT_FRACTIONAL_SECOND_FIELD, + DAY_OF_WEEK_FIELD = UDAT_DAY_OF_WEEK_FIELD, + DAY_OF_YEAR_FIELD = UDAT_DAY_OF_YEAR_FIELD, + DAY_OF_WEEK_IN_MONTH_FIELD = UDAT_DAY_OF_WEEK_IN_MONTH_FIELD, + WEEK_OF_YEAR_FIELD = UDAT_WEEK_OF_YEAR_FIELD, + WEEK_OF_MONTH_FIELD = UDAT_WEEK_OF_MONTH_FIELD, + AM_PM_FIELD = UDAT_AM_PM_FIELD, + HOUR1_FIELD = UDAT_HOUR1_FIELD, + HOUR0_FIELD = UDAT_HOUR0_FIELD, + TIMEZONE_FIELD = UDAT_TIMEZONE_FIELD + }; +}; + +inline UnicodeString& +DateFormat::format(const Formattable& obj, + UnicodeString& appendTo, + UErrorCode& status) const { + return Format::format(obj, appendTo, status); +} +U_NAMESPACE_END + +#endif /* #if !UCONFIG_NO_FORMATTING */ + +#endif // _DATEFMT +//eof diff --git a/deps/prebuilt/include/icu/unicode/dtfmtsym.h b/deps/prebuilt/include/icu/unicode/dtfmtsym.h new file mode 100644 index 0000000000..9fbbafb0a3 --- /dev/null +++ b/deps/prebuilt/include/icu/unicode/dtfmtsym.h @@ -0,0 +1,748 @@ +/* +******************************************************************************** +* Copyright (C) 1997-2011, International Business Machines +* Corporation and others. All Rights Reserved. +******************************************************************************** +* +* File DTFMTSYM.H +* +* Modification History: +* +* Date Name Description +* 02/19/97 aliu Converted from java. +* 07/21/98 stephen Added getZoneIndex() +* Changed to match C++ conventions +******************************************************************************** +*/ + +#ifndef DTFMTSYM_H +#define DTFMTSYM_H + +#include "unicode/utypes.h" + +#if !UCONFIG_NO_FORMATTING + +#include "unicode/calendar.h" +#include "unicode/uobject.h" +#include "unicode/locid.h" +#include "unicode/ures.h" + +/** + * \file + * \brief C++ API: Symbols for formatting dates. + */ + +U_NAMESPACE_BEGIN + +/* forward declaration */ +class SimpleDateFormat; +class Hashtable; + +/** + * DateFormatSymbols is a public class for encapsulating localizable date-time + * formatting data -- including timezone data. DateFormatSymbols is used by + * DateFormat and SimpleDateFormat. + *

+ * Rather than first creating a DateFormatSymbols to get a date-time formatter + * by using a SimpleDateFormat constructor, clients are encouraged to create a + * date-time formatter using the getTimeInstance(), getDateInstance(), or + * getDateTimeInstance() method in DateFormat. Each of these methods can return a + * date/time formatter initialized with a default format pattern along with the + * date-time formatting data for a given or default locale. After a formatter is + * created, clients may modify the format pattern using the setPattern function + * as so desired. For more information on using these formatter factory + * functions, see DateFormat. + *

+ * If clients decide to create a date-time formatter with a particular format + * pattern and locale, they can do so with new SimpleDateFormat(aPattern, + * new DateFormatSymbols(aLocale)). This will load the appropriate date-time + * formatting data from the locale. + *

+ * DateFormatSymbols objects are clonable. When clients obtain a + * DateFormatSymbols object, they can feel free to modify the date-time + * formatting data as necessary. For instance, clients can + * replace the localized date-time format pattern characters with the ones that + * they feel easy to remember. Or they can change the representative cities + * originally picked by default to using their favorite ones. + *

+ * DateFormatSymbols are not expected to be subclassed. Data for a calendar is + * loaded out of resource bundles. The 'type' parameter indicates the type of + * calendar, for example, "gregorian" or "japanese". If the type is not gregorian + * (or NULL, or an empty string) then the type is appended to the resource name, + * for example, 'Eras_japanese' instead of 'Eras'. If the resource 'Eras_japanese' did + * not exist (even in root), then this class will fall back to just 'Eras', that is, + * Gregorian data. Therefore, the calendar implementor MUST ensure that the root + * locale at least contains any resources that are to be particularized for the + * calendar type. + */ +class U_I18N_API DateFormatSymbols : public UObject { +public: + /** + * Construct a DateFormatSymbols object by loading format data from + * resources for the default locale, in the default calendar (Gregorian). + *

+ * NOTE: This constructor will never fail; if it cannot get resource + * data for the default locale, it will return a last-resort object + * based on hard-coded strings. + * + * @param status Status code. Failure + * results if the resources for the default cannot be + * found or cannot be loaded + * @stable ICU 2.0 + */ + DateFormatSymbols(UErrorCode& status); + + /** + * Construct a DateFormatSymbols object by loading format data from + * resources for the given locale, in the default calendar (Gregorian). + * + * @param locale Locale to load format data from. + * @param status Status code. Failure + * results if the resources for the locale cannot be + * found or cannot be loaded + * @stable ICU 2.0 + */ + DateFormatSymbols(const Locale& locale, + UErrorCode& status); + + /** + * Construct a DateFormatSymbols object by loading format data from + * resources for the default locale, in the default calendar (Gregorian). + *

+ * NOTE: This constructor will never fail; if it cannot get resource + * data for the default locale, it will return a last-resort object + * based on hard-coded strings. + * + * @param type Type of calendar (as returned by Calendar::getType). + * Will be used to access the correct set of strings. + * (NULL or empty string defaults to "gregorian".) + * @param status Status code. Failure + * results if the resources for the default cannot be + * found or cannot be loaded + * @internal + */ + DateFormatSymbols(const char *type, UErrorCode& status); + + /** + * Construct a DateFormatSymbols object by loading format data from + * resources for the given locale, in the default calendar (Gregorian). + * + * @param locale Locale to load format data from. + * @param type Type of calendar (as returned by Calendar::getType). + * Will be used to access the correct set of strings. + * (NULL or empty string defaults to "gregorian".) + * @param status Status code. Failure + * results if the resources for the locale cannot be + * found or cannot be loaded + * @internal + */ + DateFormatSymbols(const Locale& locale, + const char *type, + UErrorCode& status); + + /** + * Copy constructor. + * @stable ICU 2.0 + */ + DateFormatSymbols(const DateFormatSymbols&); + + /** + * Assignment operator. + * @stable ICU 2.0 + */ + DateFormatSymbols& operator=(const DateFormatSymbols&); + + /** + * Destructor. This is nonvirtual because this class is not designed to be + * subclassed. + * @stable ICU 2.0 + */ + virtual ~DateFormatSymbols(); + + /** + * Return true if another object is semantically equal to this one. + * + * @param other the DateFormatSymbols object to be compared with. + * @return true if other is semantically equal to this. + * @stable ICU 2.0 + */ + UBool operator==(const DateFormatSymbols& other) const; + + /** + * Return true if another object is semantically unequal to this one. + * + * @param other the DateFormatSymbols object to be compared with. + * @return true if other is semantically unequal to this. + * @stable ICU 2.0 + */ + UBool operator!=(const DateFormatSymbols& other) const { return !operator==(other); } + + /** + * Gets abbreviated era strings. For example: "AD" and "BC". + * + * @param count Filled in with length of the array. + * @return the era strings. + * @stable ICU 2.0 + */ + const UnicodeString* getEras(int32_t& count) const; + + /** + * Sets abbreviated era strings. For example: "AD" and "BC". + * @param eras Array of era strings (DateFormatSymbols retains ownership.) + * @param count Filled in with length of the array. + * @stable ICU 2.0 + */ + void setEras(const UnicodeString* eras, int32_t count); + + /** + * Gets era name strings. For example: "Anno Domini" and "Before Christ". + * + * @param count Filled in with length of the array. + * @return the era name strings. + * @stable ICU 3.4 + */ + const UnicodeString* getEraNames(int32_t& count) const; + + /** + * Sets era name strings. For example: "Anno Domini" and "Before Christ". + * @param eraNames Array of era name strings (DateFormatSymbols retains ownership.) + * @param count Filled in with length of the array. + * @stable ICU 3.6 + */ + void setEraNames(const UnicodeString* eraNames, int32_t count); + + /** + * Gets narrow era strings. For example: "A" and "B". + * + * @param count Filled in with length of the array. + * @return the narrow era strings. + * @stable ICU 4.2 + */ + const UnicodeString* getNarrowEras(int32_t& count) const; + + /** + * Sets narrow era strings. For example: "A" and "B". + * @param narrowEras Array of narrow era strings (DateFormatSymbols retains ownership.) + * @param count Filled in with length of the array. + * @stable ICU 4.2 + */ + void setNarrowEras(const UnicodeString* narrowEras, int32_t count); + + /** + * Gets month strings. For example: "January", "February", etc. + * @param count Filled in with length of the array. + * @return the month strings. (DateFormatSymbols retains ownership.) + * @stable ICU 2.0 + */ + const UnicodeString* getMonths(int32_t& count) const; + + /** + * Sets month strings. For example: "January", "February", etc. + * + * @param months the new month strings. (not adopted; caller retains ownership) + * @param count Filled in with length of the array. + * @stable ICU 2.0 + */ + void setMonths(const UnicodeString* months, int32_t count); + + /** + * Gets short month strings. For example: "Jan", "Feb", etc. + * + * @param count Filled in with length of the array. + * @return the short month strings. (DateFormatSymbols retains ownership.) + * @stable ICU 2.0 + */ + const UnicodeString* getShortMonths(int32_t& count) const; + + /** + * Sets short month strings. For example: "Jan", "Feb", etc. + * @param count Filled in with length of the array. + * @param shortMonths the new short month strings. (not adopted; caller retains ownership) + * @stable ICU 2.0 + */ + void setShortMonths(const UnicodeString* shortMonths, int32_t count); + + /** + * Selector for date formatting context + * @stable ICU 3.6 + */ + enum DtContextType { + FORMAT, + STANDALONE, + DT_CONTEXT_COUNT + }; + + /** + * Selector for date formatting width + * @stable ICU 3.6 + */ + enum DtWidthType { + ABBREVIATED, + WIDE, + NARROW, + DT_WIDTH_COUNT + }; + + /** + * Gets month strings by width and context. For example: "January", "February", etc. + * @param count Filled in with length of the array. + * @param context The formatting context, either FORMAT or STANDALONE + * @param width The width of returned strings, either WIDE, ABBREVIATED, or NARROW. + * @return the month strings. (DateFormatSymbols retains ownership.) + * @stable ICU 3.4 + */ + const UnicodeString* getMonths(int32_t& count, DtContextType context, DtWidthType width) const; + + /** + * Sets month strings by width and context. For example: "January", "February", etc. + * + * @param months The new month strings. (not adopted; caller retains ownership) + * @param count Filled in with length of the array. + * @param context The formatting context, either FORMAT or STANDALONE + * @param width The width of returned strings, either WIDE, ABBREVIATED, or NARROW. + * @stable ICU 3.6 + */ + void setMonths(const UnicodeString* months, int32_t count, DtContextType context, DtWidthType width); + + /** + * Gets weekday strings. For example: "Sunday", "Monday", etc. + * @param count Filled in with length of the array. + * @return the weekday strings. (DateFormatSymbols retains ownership.) + * @stable ICU 2.0 + */ + const UnicodeString* getWeekdays(int32_t& count) const; + + + /** + * Sets weekday strings. For example: "Sunday", "Monday", etc. + * @param weekdays the new weekday strings. (not adopted; caller retains ownership) + * @param count Filled in with length of the array. + * @stable ICU 2.0 + */ + void setWeekdays(const UnicodeString* weekdays, int32_t count); + + /** + * Gets short weekday strings. For example: "Sun", "Mon", etc. + * @param count Filled in with length of the array. + * @return the short weekday strings. (DateFormatSymbols retains ownership.) + * @stable ICU 2.0 + */ + const UnicodeString* getShortWeekdays(int32_t& count) const; + + /** + * Sets short weekday strings. For example: "Sun", "Mon", etc. + * @param shortWeekdays the new short weekday strings. (not adopted; caller retains ownership) + * @param count Filled in with length of the array. + * @stable ICU 2.0 + */ + void setShortWeekdays(const UnicodeString* shortWeekdays, int32_t count); + + /** + * Gets weekday strings by width and context. For example: "Sunday", "Monday", etc. + * @param count Filled in with length of the array. + * @param context The formatting context, either FORMAT or STANDALONE + * @param width The width of returned strings, either WIDE, ABBREVIATED, or NARROW + * @return the month strings. (DateFormatSymbols retains ownership.) + * @stable ICU 3.4 + */ + const UnicodeString* getWeekdays(int32_t& count, DtContextType context, DtWidthType width) const; + + /** + * Sets weekday strings by width and context. For example: "Sunday", "Monday", etc. + * @param weekdays The new weekday strings. (not adopted; caller retains ownership) + * @param count Filled in with length of the array. + * @param context The formatting context, either FORMAT or STANDALONE + * @param width The width of returned strings, either WIDE, ABBREVIATED, or NARROW + * @stable ICU 3.6 + */ + void setWeekdays(const UnicodeString* weekdays, int32_t count, DtContextType context, DtWidthType width); + + /** + * Gets quarter strings by width and context. For example: "1st Quarter", "2nd Quarter", etc. + * @param count Filled in with length of the array. + * @param context The formatting context, either FORMAT or STANDALONE + * @param width The width of returned strings, either WIDE or ABBREVIATED. There + * are no NARROW quarters. + * @return the quarter strings. (DateFormatSymbols retains ownership.) + * @stable ICU 3.6 + */ + const UnicodeString* getQuarters(int32_t& count, DtContextType context, DtWidthType width) const; + + /** + * Sets quarter strings by width and context. For example: "1st Quarter", "2nd Quarter", etc. + * + * @param quarters The new quarter strings. (not adopted; caller retains ownership) + * @param count Filled in with length of the array. + * @param context The formatting context, either FORMAT or STANDALONE + * @param width The width of returned strings, either WIDE or ABBREVIATED. There + * are no NARROW quarters. + * @stable ICU 3.6 + */ + void setQuarters(const UnicodeString* quarters, int32_t count, DtContextType context, DtWidthType width); + + /** + * Gets AM/PM strings. For example: "AM" and "PM". + * @param count Filled in with length of the array. + * @return the weekday strings. (DateFormatSymbols retains ownership.) + * @stable ICU 2.0 + */ + const UnicodeString* getAmPmStrings(int32_t& count) const; + + /** + * Sets ampm strings. For example: "AM" and "PM". + * @param ampms the new ampm strings. (not adopted; caller retains ownership) + * @param count Filled in with length of the array. + * @stable ICU 2.0 + */ + void setAmPmStrings(const UnicodeString* ampms, int32_t count); + + /** + * Gets timezone strings. These strings are stored in a 2-dimensional array. + * @param rowCount Output param to receive number of rows. + * @param columnCount Output param to receive number of columns. + * @return The timezone strings as a 2-d array. (DateFormatSymbols retains ownership.) + * @deprecated ICU 3.6 + */ + const UnicodeString** getZoneStrings(int32_t& rowCount, int32_t& columnCount) const; + + /** + * Sets timezone strings. These strings are stored in a 2-dimensional array. + *

Note: SimpleDateFormat no longer use the zone strings stored in + * a DateFormatSymbols. Therefore, the time zone strings set by this mthod + * have no effects in an instance of SimpleDateFormat for formatting time + * zones. + * @param strings The timezone strings as a 2-d array to be copied. (not adopted; caller retains ownership) + * @param rowCount The number of rows (count of first index). + * @param columnCount The number of columns (count of second index). + * @stable ICU 2.0 + */ + void setZoneStrings(const UnicodeString* const* strings, int32_t rowCount, int32_t columnCount); + + /** + * Get the non-localized date-time pattern characters. + * @return the non-localized date-time pattern characters + * @stable ICU 2.0 + */ + static const UChar * U_EXPORT2 getPatternUChars(void); + + /** + * Gets localized date-time pattern characters. For example: 'u', 't', etc. + *

+ * Note: ICU no longer provides localized date-time pattern characters for a locale + * starting ICU 3.8. This method returns the non-localized date-time pattern + * characters unless user defined localized data is set by setLocalPatternChars. + * @param result Output param which will receive the localized date-time pattern characters. + * @return A reference to 'result'. + * @stable ICU 2.0 + */ + UnicodeString& getLocalPatternChars(UnicodeString& result) const; + + /** + * Sets localized date-time pattern characters. For example: 'u', 't', etc. + * @param newLocalPatternChars the new localized date-time + * pattern characters. + * @stable ICU 2.0 + */ + void setLocalPatternChars(const UnicodeString& newLocalPatternChars); + + /** + * Returns the locale for this object. Two flavors are available: + * valid and actual locale. + * @stable ICU 2.8 + */ + Locale getLocale(ULocDataLocaleType type, UErrorCode& status) const; + + /** + * ICU "poor man's RTTI", returns a UClassID for the actual class. + * + * @stable ICU 2.2 + */ + virtual UClassID getDynamicClassID() const; + + /** + * ICU "poor man's RTTI", returns a UClassID for this class. + * + * @stable ICU 2.2 + */ + static UClassID U_EXPORT2 getStaticClassID(); + +private: + + friend class SimpleDateFormat; + friend class DateFormatSymbolsSingleSetter; // see udat.cpp + + /** + * Abbreviated era strings. For example: "AD" and "BC". + */ + UnicodeString* fEras; + int32_t fErasCount; + + /** + * Era name strings. For example: "Anno Domini" and "Before Christ". + */ + UnicodeString* fEraNames; + int32_t fEraNamesCount; + + /** + * Narrow era strings. For example: "A" and "B". + */ + UnicodeString* fNarrowEras; + int32_t fNarrowErasCount; + + /** + * Month strings. For example: "January", "February", etc. + */ + UnicodeString* fMonths; + int32_t fMonthsCount; + + /** + * Short month strings. For example: "Jan", "Feb", etc. + */ + UnicodeString* fShortMonths; + int32_t fShortMonthsCount; + + /** + * Narrow month strings. For example: "J", "F", etc. + */ + UnicodeString* fNarrowMonths; + int32_t fNarrowMonthsCount; + + /** + * Standalone Month strings. For example: "January", "February", etc. + */ + UnicodeString* fStandaloneMonths; + int32_t fStandaloneMonthsCount; + + /** + * Standalone Short month strings. For example: "Jan", "Feb", etc. + */ + UnicodeString* fStandaloneShortMonths; + int32_t fStandaloneShortMonthsCount; + + /** + * Standalone Narrow month strings. For example: "J", "F", etc. + */ + UnicodeString* fStandaloneNarrowMonths; + int32_t fStandaloneNarrowMonthsCount; + + /** + * Weekday strings. For example: "Sunday", "Monday", etc. + */ + UnicodeString* fWeekdays; + int32_t fWeekdaysCount; + + /** + * Short weekday strings. For example: "Sun", "Mon", etc. + */ + UnicodeString* fShortWeekdays; + int32_t fShortWeekdaysCount; + + /** + * Narrow weekday strings. For example: "Sun", "Mon", etc. + */ + UnicodeString* fNarrowWeekdays; + int32_t fNarrowWeekdaysCount; + + /** + * Standalone Weekday strings. For example: "Sunday", "Monday", etc. + */ + UnicodeString* fStandaloneWeekdays; + int32_t fStandaloneWeekdaysCount; + + /** + * Standalone Short weekday strings. For example: "Sun", "Mon", etc. + */ + UnicodeString* fStandaloneShortWeekdays; + int32_t fStandaloneShortWeekdaysCount; + + /** + * Standalone Narrow weekday strings. For example: "Sun", "Mon", etc. + */ + UnicodeString* fStandaloneNarrowWeekdays; + int32_t fStandaloneNarrowWeekdaysCount; + + /** + * Ampm strings. For example: "AM" and "PM". + */ + UnicodeString* fAmPms; + int32_t fAmPmsCount; + + /** + * Quarter strings. For example: "1st quarter", "2nd quarter", etc. + */ + UnicodeString *fQuarters; + int32_t fQuartersCount; + + /** + * Short quarters. For example: "Q1", "Q2", etc. + */ + UnicodeString *fShortQuarters; + int32_t fShortQuartersCount; + + /** + * Standalone quarter strings. For example: "1st quarter", "2nd quarter", etc. + */ + UnicodeString *fStandaloneQuarters; + int32_t fStandaloneQuartersCount; + + /** + * Standalone short quarter strings. For example: "Q1", "Q2", etc. + */ + UnicodeString *fStandaloneShortQuarters; + int32_t fStandaloneShortQuartersCount; + + /** + * Localized names of time zones in this locale. This is a + * two-dimensional array of strings of size n by m, + * where m is at least 5 and up to 7. Each of the n rows is an + * entry containing the localized names for a single TimeZone. + * + * Each such row contains (with i ranging from 0..n-1): + * + * zoneStrings[i][0] - time zone ID + * example: America/Los_Angeles + * zoneStrings[i][1] - long name of zone in standard time + * example: Pacific Standard Time + * zoneStrings[i][2] - short name of zone in standard time + * example: PST + * zoneStrings[i][3] - long name of zone in daylight savings time + * example: Pacific Daylight Time + * zoneStrings[i][4] - short name of zone in daylight savings time + * example: PDT + * zoneStrings[i][5] - location name of zone + * example: United States (Los Angeles) + * zoneStrings[i][6] - long generic name of zone + * example: Pacific Time + * zoneStrings[i][7] - short generic of zone + * example: PT + * + * The zone ID is not localized; it corresponds to the ID + * value associated with a system time zone object. All other entries + * are localized names. If a zone does not implement daylight savings + * time, the daylight savings time names are ignored. + * + * Note:CLDR 1.5 introduced metazone and its historical mappings. + * This simple two-dimensional array is no longer sufficient to represent + * localized names and its historic changes. Since ICU 3.8.1, localized + * zone names extracted from ICU locale data is stored in a ZoneStringFormat + * instance. But we still need to support the old way of customizing + * localized zone names, so we keep this field for the purpose. + */ + UnicodeString **fZoneStrings; // Zone string array set by setZoneStrings + UnicodeString **fLocaleZoneStrings; // Zone string array created by the locale + int32_t fZoneStringsRowCount; + int32_t fZoneStringsColCount; + + Locale fZSFLocale; // Locale used for getting ZoneStringFormat + + /** + * String used for localized GMT. For example, "GMT" + */ + UnicodeString fGmtZero; + + /** + * Pattern string used for localized time zone GMT format. For example, "GMT{0}" + */ + UnicodeString fGmtFormat; + + /** + * Pattern strings used for formatting zone offset in a localized time zone GMT string. + */ + UnicodeString *fGmtHourFormats; + int32_t fGmtHourFormatsCount; + + enum GMTHourType { + GMT_NEGATIVE_HMS = 0, + GMT_NEGATIVE_HM, + GMT_POSITIVE_HMS, + GMT_POSITIVE_HM, + GMT_HOUR_COUNT + }; + + /** + * Localized date-time pattern characters. For example: use 'u' as 'y'. + */ + UnicodeString fLocalPatternChars; + +private: + /** valid/actual locale information + * these are always ICU locales, so the length should not be a problem + */ + char validLocale[ULOC_FULLNAME_CAPACITY]; + char actualLocale[ULOC_FULLNAME_CAPACITY]; + + DateFormatSymbols(); // default constructor not implemented + + /** + * Called by the constructors to actually load data from the resources + * + * @param locale The locale to get symbols for. + * @param type Calendar Type (as from Calendar::getType()) + * @param status Input/output parameter, set to success or + * failure code upon return. + * @param useLastResortData determine if use last resort data + */ + void initializeData(const Locale& locale, const char *type, UErrorCode& status, UBool useLastResortData = FALSE); + + /** + * Copy or alias an array in another object, as appropriate. + * + * @param dstArray the copy destination array. + * @param dstCount fill in with the lenth of 'dstArray'. + * @param srcArray the source array to be copied. + * @param srcCount the length of items to be copied from the 'srcArray'. + */ + static void assignArray(UnicodeString*& dstArray, + int32_t& dstCount, + const UnicodeString* srcArray, + int32_t srcCount); + + /** + * Return true if the given arrays' contents are equal, or if the arrays are + * identical (pointers are equal). + * + * @param array1 one array to be compared with. + * @param array2 another array to be compared with. + * @param count the length of items to be copied. + * @return true if the given arrays' contents are equal, or if the arrays are + * identical (pointers are equal). + */ + static UBool arrayCompare(const UnicodeString* array1, + const UnicodeString* array2, + int32_t count); + + /** + * Create a copy, in fZoneStrings, of the given zone strings array. The + * member variables fZoneStringsRowCount and fZoneStringsColCount should be + * set already by the caller. + */ + void createZoneStrings(const UnicodeString *const * otherStrings); + + /** + * Delete all the storage owned by this object. + */ + void dispose(void); + + /** + * Copy all of the other's data to this. + * @param other the object to be copied. + */ + void copyData(const DateFormatSymbols& other); + + /** + * Create zone strings array by locale if not yet available + */ + void initZoneStringsArray(void); + + /** + * Delete just the zone strings. + */ + void disposeZoneStrings(void); +}; + +U_NAMESPACE_END + +#endif /* #if !UCONFIG_NO_FORMATTING */ + +#endif // _DTFMTSYM +//eof diff --git a/deps/prebuilt/include/icu/unicode/dtptngen.h b/deps/prebuilt/include/icu/unicode/dtptngen.h new file mode 100644 index 0000000000..1a0f70bc84 --- /dev/null +++ b/deps/prebuilt/include/icu/unicode/dtptngen.h @@ -0,0 +1,474 @@ +/* +******************************************************************************* +* Copyright (C) 2007-2010, International Business Machines Corporation and +* others. All Rights Reserved. +******************************************************************************* +* +* File DTPTNGEN.H +* +******************************************************************************* +*/ + +#ifndef __DTPTNGEN_H__ +#define __DTPTNGEN_H__ + +#include "unicode/datefmt.h" +#include "unicode/locid.h" +#include "unicode/udat.h" +#include "unicode/udatpg.h" + +U_NAMESPACE_BEGIN + +/** + * \file + * \brief C++ API: Date/Time Pattern Generator + */ + + +class Hashtable; +class FormatParser; +class DateTimeMatcher; +class DistanceInfo; +class PatternMap; +class PtnSkeleton; + +/** + * This class provides flexible generation of date format patterns, like "yy-MM-dd". + * The user can build up the generator by adding successive patterns. Once that + * is done, a query can be made using a "skeleton", which is a pattern which just + * includes the desired fields and lengths. The generator will return the "best fit" + * pattern corresponding to that skeleton. + *

The main method people will use is getBestPattern(String skeleton), + * since normally this class is pre-built with data from a particular locale. + * However, generators can be built directly from other data as well. + *

Issue: may be useful to also have a function that returns the list of + * fields in a pattern, in order, since we have that internally. + * That would be useful for getting the UI order of field elements. + * @stable ICU 3.8 +**/ +class U_I18N_API DateTimePatternGenerator : public UObject { +public: + /** + * Construct a flexible generator according to default locale. + * @param status Output param set to success/failure code on exit, + * which must not indicate a failure before the function call. + * @stable ICU 3.8 + */ + static DateTimePatternGenerator* U_EXPORT2 createInstance(UErrorCode& status); + + /** + * Construct a flexible generator according to data for a given locale. + * @param uLocale + * @param status Output param set to success/failure code on exit, + * which must not indicate a failure before the function call. + * @stable ICU 3.8 + */ + static DateTimePatternGenerator* U_EXPORT2 createInstance(const Locale& uLocale, UErrorCode& status); + + /** + * Create an empty generator, to be constructed with addPattern(...) etc. + * @param status Output param set to success/failure code on exit, + * which must not indicate a failure before the function call. + * @stable ICU 3.8 + */ + static DateTimePatternGenerator* U_EXPORT2 createEmptyInstance(UErrorCode& status); + + /** + * Destructor. + * @stable ICU 3.8 + */ + virtual ~DateTimePatternGenerator(); + + /** + * Clone DateTimePatternGenerator object. Clients are responsible for + * deleting the DateTimePatternGenerator object cloned. + * @stable ICU 3.8 + */ + DateTimePatternGenerator* clone() const; + + /** + * Return true if another object is semantically equal to this one. + * + * @param other the DateTimePatternGenerator object to be compared with. + * @return true if other is semantically equal to this. + * @stable ICU 3.8 + */ + UBool operator==(const DateTimePatternGenerator& other) const; + + /** + * Return true if another object is semantically unequal to this one. + * + * @param other the DateTimePatternGenerator object to be compared with. + * @return true if other is semantically unequal to this. + * @stable ICU 3.8 + */ + UBool operator!=(const DateTimePatternGenerator& other) const; + + /** + * Utility to return a unique skeleton from a given pattern. For example, + * both "MMM-dd" and "dd/MMM" produce the skeleton "MMMdd". + * + * @param pattern Input pattern, such as "dd/MMM" + * @param status Output param set to success/failure code on exit, + * which must not indicate a failure before the function call. + * @return skeleton such as "MMMdd" + * @stable ICU 3.8 + */ + UnicodeString getSkeleton(const UnicodeString& pattern, UErrorCode& status); + + /** + * Utility to return a unique base skeleton from a given pattern. This is + * the same as the skeleton, except that differences in length are minimized + * so as to only preserve the difference between string and numeric form. So + * for example, both "MMM-dd" and "d/MMM" produce the skeleton "MMMd" + * (notice the single d). + * + * @param pattern Input pattern, such as "dd/MMM" + * @param status Output param set to success/failure code on exit, + * which must not indicate a failure before the function call. + * @return base skeleton, such as "Md" + * @stable ICU 3.8 + */ + UnicodeString getBaseSkeleton(const UnicodeString& pattern, UErrorCode& status); + + /** + * Adds a pattern to the generator. If the pattern has the same skeleton as + * an existing pattern, and the override parameter is set, then the previous + * value is overriden. Otherwise, the previous value is retained. In either + * case, the conflicting status is set and previous vale is stored in + * conflicting pattern. + *

+ * Note that single-field patterns (like "MMM") are automatically added, and + * don't need to be added explicitly! + * + * @param pattern Input pattern, such as "dd/MMM" + * @param override When existing values are to be overridden use true, + * otherwise use false. + * @param conflictingPattern Previous pattern with the same skeleton. + * @param status Output param set to success/failure code on exit, + * which must not indicate a failure before the function call. + * @return conflicting status. The value could be UDATPG_NO_CONFLICT, + * UDATPG_BASE_CONFLICT or UDATPG_CONFLICT. + * @stable ICU 3.8 + */ + UDateTimePatternConflict addPattern(const UnicodeString& pattern, + UBool override, + UnicodeString& conflictingPattern, + UErrorCode& status); + + /** + * An AppendItem format is a pattern used to append a field if there is no + * good match. For example, suppose that the input skeleton is "GyyyyMMMd", + * and there is no matching pattern internally, but there is a pattern + * matching "yyyyMMMd", say "d-MM-yyyy". Then that pattern is used, plus the + * G. The way these two are conjoined is by using the AppendItemFormat for G + * (era). So if that value is, say "{0}, {1}" then the final resulting + * pattern is "d-MM-yyyy, G". + *

+ * There are actually three available variables: {0} is the pattern so far, + * {1} is the element we are adding, and {2} is the name of the element. + *

+ * This reflects the way that the CLDR data is organized. + * + * @param field such as UDATPG_ERA_FIELD. + * @param value pattern, such as "{0}, {1}" + * @stable ICU 3.8 + */ + void setAppendItemFormat(UDateTimePatternField field, const UnicodeString& value); + + /** + * Getter corresponding to setAppendItemFormat. Values below 0 or at or + * above UDATPG_FIELD_COUNT are illegal arguments. + * + * @param field such as UDATPG_ERA_FIELD. + * @return append pattern for field + * @stable ICU 3.8 + */ + const UnicodeString& getAppendItemFormat(UDateTimePatternField field) const; + + /** + * Sets the names of field, eg "era" in English for ERA. These are only + * used if the corresponding AppendItemFormat is used, and if it contains a + * {2} variable. + *

+ * This reflects the way that the CLDR data is organized. + * + * @param field such as UDATPG_ERA_FIELD. + * @param value name of the field + * @stable ICU 3.8 + */ + void setAppendItemName(UDateTimePatternField field, const UnicodeString& value); + + /** + * Getter corresponding to setAppendItemNames. Values below 0 or at or above + * UDATPG_FIELD_COUNT are illegal arguments. + * + * @param field such as UDATPG_ERA_FIELD. + * @return name for field + * @stable ICU 3.8 + */ + const UnicodeString& getAppendItemName(UDateTimePatternField field) const; + + /** + * The date time format is a message format pattern used to compose date and + * time patterns. The default value is "{0} {1}", where {0} will be replaced + * by the date pattern and {1} will be replaced by the time pattern. + *

+ * This is used when the input skeleton contains both date and time fields, + * but there is not a close match among the added patterns. For example, + * suppose that this object was created by adding "dd-MMM" and "hh:mm", and + * its datetimeFormat is the default "{0} {1}". Then if the input skeleton + * is "MMMdhmm", there is not an exact match, so the input skeleton is + * broken up into two components "MMMd" and "hmm". There are close matches + * for those two skeletons, so the result is put together with this pattern, + * resulting in "d-MMM h:mm". + * + * @param dateTimeFormat + * message format pattern, here {0} will be replaced by the date + * pattern and {1} will be replaced by the time pattern. + * @stable ICU 3.8 + */ + void setDateTimeFormat(const UnicodeString& dateTimeFormat); + + /** + * Getter corresponding to setDateTimeFormat. + * @return DateTimeFormat. + * @stable ICU 3.8 + */ + const UnicodeString& getDateTimeFormat() const; + + /** + * Return the best pattern matching the input skeleton. It is guaranteed to + * have all of the fields in the skeleton. + * + * @param skeleton + * The skeleton is a pattern containing only the variable fields. + * For example, "MMMdd" and "mmhh" are skeletons. + * @param status Output param set to success/failure code on exit, + * which must not indicate a failure before the function call. + * @return bestPattern + * The best pattern found from the given skeleton. + * @stable ICU 3.8 + */ + UnicodeString getBestPattern(const UnicodeString& skeleton, UErrorCode& status); + + + /** + * Return the best pattern matching the input skeleton. It is guaranteed to + * have all of the fields in the skeleton. + * + * @param skeleton + * The skeleton is a pattern containing only the variable fields. + * For example, "MMMdd" and "mmhh" are skeletons. + * @param options + * Options for forcing the length of specified fields in the + * returned pattern to match those in the skeleton (when this + * would not happen otherwise). For default behavior, use + * UDATPG_MATCH_NO_OPTIONS. + * @param status + * Output param set to success/failure code on exit, + * which must not indicate a failure before the function call. + * @return bestPattern + * The best pattern found from the given skeleton. + * @stable ICU 4.4 + */ + UnicodeString getBestPattern(const UnicodeString& skeleton, + UDateTimePatternMatchOptions options, + UErrorCode& status); + + + /** + * Adjusts the field types (width and subtype) of a pattern to match what is + * in a skeleton. That is, if you supply a pattern like "d-M H:m", and a + * skeleton of "MMMMddhhmm", then the input pattern is adjusted to be + * "dd-MMMM hh:mm". This is used internally to get the best match for the + * input skeleton, but can also be used externally. + * + * @param pattern Input pattern + * @param skeleton + * The skeleton is a pattern containing only the variable fields. + * For example, "MMMdd" and "mmhh" are skeletons. + * @param status Output param set to success/failure code on exit, + * which must not indicate a failure before the function call. + * @return pattern adjusted to match the skeleton fields widths and subtypes. + * @stable ICU 3.8 + */ + UnicodeString replaceFieldTypes(const UnicodeString& pattern, + const UnicodeString& skeleton, + UErrorCode& status); + + /** + * Adjusts the field types (width and subtype) of a pattern to match what is + * in a skeleton. That is, if you supply a pattern like "d-M H:m", and a + * skeleton of "MMMMddhhmm", then the input pattern is adjusted to be + * "dd-MMMM hh:mm". This is used internally to get the best match for the + * input skeleton, but can also be used externally. + * + * @param pattern Input pattern + * @param skeleton + * The skeleton is a pattern containing only the variable fields. + * For example, "MMMdd" and "mmhh" are skeletons. + * @param options + * Options controlling whether the length of specified fields in the + * pattern are adjusted to match those in the skeleton (when this + * would not happen otherwise). For default behavior, use + * UDATPG_MATCH_NO_OPTIONS. + * @param status + * Output param set to success/failure code on exit, + * which must not indicate a failure before the function call. + * @return pattern adjusted to match the skeleton fields widths and subtypes. + * @stable ICU 4.4 + */ + UnicodeString replaceFieldTypes(const UnicodeString& pattern, + const UnicodeString& skeleton, + UDateTimePatternMatchOptions options, + UErrorCode& status); + + /** + * Return a list of all the skeletons (in canonical form) from this class. + * + * Call getPatternForSkeleton() to get the corresponding pattern. + * + * @param status Output param set to success/failure code on exit, + * which must not indicate a failure before the function call. + * @return StringEnumeration with the skeletons. + * The caller must delete the object. + * @stable ICU 3.8 + */ + StringEnumeration* getSkeletons(UErrorCode& status) const; + + /** + * Get the pattern corresponding to a given skeleton. + * @param skeleton + * @return pattern corresponding to a given skeleton. + * @stable ICU 3.8 + */ + const UnicodeString& getPatternForSkeleton(const UnicodeString& skeleton) const; + + /** + * Return a list of all the base skeletons (in canonical form) from this class. + * + * @param status Output param set to success/failure code on exit, + * which must not indicate a failure before the function call. + * @return a StringEnumeration with the base skeletons. + * The caller must delete the object. + * @stable ICU 3.8 + */ + StringEnumeration* getBaseSkeletons(UErrorCode& status) const; + + /** + * Return a list of redundant patterns are those which if removed, make no + * difference in the resulting getBestPattern values. This method returns a + * list of them, to help check the consistency of the patterns used to build + * this generator. + * + * @param status Output param set to success/failure code on exit, + * which must not indicate a failure before the function call. + * @return a StringEnumeration with the redundant pattern. + * The caller must delete the object. + * @internal ICU 3.8 + */ + StringEnumeration* getRedundants(UErrorCode& status); + + /** + * The decimal value is used in formatting fractions of seconds. If the + * skeleton contains fractional seconds, then this is used with the + * fractional seconds. For example, suppose that the input pattern is + * "hhmmssSSSS", and the best matching pattern internally is "H:mm:ss", and + * the decimal string is ",". Then the resulting pattern is modified to be + * "H:mm:ss,SSSS" + * + * @param decimal + * @stable ICU 3.8 + */ + void setDecimal(const UnicodeString& decimal); + + /** + * Getter corresponding to setDecimal. + * @return UnicodeString corresponding to the decimal point + * @stable ICU 3.8 + */ + const UnicodeString& getDecimal() const; + + /** + * ICU "poor man's RTTI", returns a UClassID for the actual class. + * + * @stable ICU 3.8 + */ + virtual UClassID getDynamicClassID() const; + + /** + * ICU "poor man's RTTI", returns a UClassID for this class. + * + * @stable ICU 3.8 + */ + static UClassID U_EXPORT2 getStaticClassID(void); + +private: + /** + * Constructor. + * @stable ICU 3.8 + */ + DateTimePatternGenerator(UErrorCode & status); + + /** + * Constructor. + * @stable ICU 3.8 + */ + DateTimePatternGenerator(const Locale& locale, UErrorCode & status); + + /** + * Copy constructor. + * @param other DateTimePatternGenerator to copy + * @stable ICU 3.8 + */ + DateTimePatternGenerator(const DateTimePatternGenerator& other); + + /** + * Default assignment operator. + * @param other DateTimePatternGenerator to copy + * @stable ICU 3.8 + */ + DateTimePatternGenerator& operator=(const DateTimePatternGenerator& other); + + Locale pLocale; // pattern locale + FormatParser *fp; + DateTimeMatcher* dtMatcher; + DistanceInfo *distanceInfo; + PatternMap *patternMap; + UnicodeString appendItemFormats[UDATPG_FIELD_COUNT]; + UnicodeString appendItemNames[UDATPG_FIELD_COUNT]; + UnicodeString dateTimeFormat; + UnicodeString decimal; + DateTimeMatcher *skipMatcher; + Hashtable *fAvailableFormatKeyHash; + UnicodeString hackPattern; + UnicodeString emptyString; + UChar fDefaultHourFormatChar; + + void initData(const Locale &locale, UErrorCode &status); + void addCanonicalItems(); + void addICUPatterns(const Locale& locale, UErrorCode& status); + void hackTimes(const UnicodeString& hackPattern, UErrorCode& status); + void addCLDRData(const Locale& locale, UErrorCode& status); + UDateTimePatternConflict addPatternWithSkeleton(const UnicodeString& pattern, const UnicodeString * skeletonToUse, UBool override, UnicodeString& conflictingPattern, UErrorCode& status); + void initHashtable(UErrorCode& status); + void setDateTimeFromCalendar(const Locale& locale, UErrorCode& status); + void setDecimalSymbols(const Locale& locale, UErrorCode& status); + UDateTimePatternField getAppendFormatNumber(const char* field) const; + UDateTimePatternField getAppendNameNumber(const char* field) const; + void getAppendName(UDateTimePatternField field, UnicodeString& value); + int32_t getCanonicalIndex(const UnicodeString& field); + const UnicodeString* getBestRaw(DateTimeMatcher& source, int32_t includeMask, DistanceInfo* missingFields, const PtnSkeleton** specifiedSkeletonPtr = 0); + UnicodeString adjustFieldTypes(const UnicodeString& pattern, const PtnSkeleton* specifiedSkeleton, UBool fixFractionalSeconds, UDateTimePatternMatchOptions options = UDATPG_MATCH_NO_OPTIONS); + UnicodeString getBestAppending(int32_t missingFields, UDateTimePatternMatchOptions options = UDATPG_MATCH_NO_OPTIONS); + int32_t getTopBitNumber(int32_t foundMask); + void setAvailableFormat(const UnicodeString &key, UErrorCode& status); + UBool isAvailableFormatSet(const UnicodeString &key) const; + void copyHashtable(Hashtable *other, UErrorCode &status); + UBool isCanonicalItem(const UnicodeString& item) const; +} ;// end class DateTimePatternGenerator + +U_NAMESPACE_END + +#endif diff --git a/deps/prebuilt/include/icu/unicode/smpdtfmt.h b/deps/prebuilt/include/icu/unicode/smpdtfmt.h new file mode 100644 index 0000000000..927729b4b1 --- /dev/null +++ b/deps/prebuilt/include/icu/unicode/smpdtfmt.h @@ -0,0 +1,1238 @@ +/* +* Copyright (C) 1997-2011, International Business Machines Corporation and +* others. All Rights Reserved. +******************************************************************************* +* +* File SMPDTFMT.H +* +* Modification History: +* +* Date Name Description +* 02/19/97 aliu Converted from java. +* 07/09/97 helena Make ParsePosition into a class. +* 07/21/98 stephen Added GMT_PLUS, GMT_MINUS +* Changed setTwoDigitStartDate to set2DigitYearStart +* Changed getTwoDigitStartDate to get2DigitYearStart +* Removed subParseLong +* Removed getZoneIndex (added in DateFormatSymbols) +* 06/14/99 stephen Removed fgTimeZoneDataSuffix +* 10/14/99 aliu Updated class doc to describe 2-digit year parsing +* {j28 4182066}. +******************************************************************************* +*/ + +#ifndef SMPDTFMT_H +#define SMPDTFMT_H + +#include "unicode/utypes.h" + +/** + * \file + * \brief C++ API: Format and parse dates in a language-independent manner. + */ + +#if !UCONFIG_NO_FORMATTING + +#include "unicode/datefmt.h" + +U_NAMESPACE_BEGIN + +class DateFormatSymbols; +class DateFormat; +class MessageFormat; +class FieldPositionHandler; +class TimeZoneFormat; + +/** + * + * SimpleDateFormat is a concrete class for formatting and parsing dates in a + * language-independent manner. It allows for formatting (millis -> text), + * parsing (text -> millis), and normalization. Formats/Parses a date or time, + * which is the standard milliseconds since 24:00 GMT, Jan 1, 1970. + *

+ * Clients are encouraged to create a date-time formatter using DateFormat::getInstance(), + * getDateInstance(), getDateInstance(), or getDateTimeInstance() rather than + * explicitly constructing an instance of SimpleDateFormat. This way, the client + * is guaranteed to get an appropriate formatting pattern for whatever locale the + * program is running in. However, if the client needs something more unusual than + * the default patterns in the locales, he can construct a SimpleDateFormat directly + * and give it an appropriate pattern (or use one of the factory methods on DateFormat + * and modify the pattern after the fact with toPattern() and applyPattern(). + *

+ * Date/Time format syntax: + *

+ * The date/time format is specified by means of a string time pattern. In this + * pattern, all ASCII letters are reserved as pattern letters, which are defined + * as the following: + *

+ * \code
+ * Symbol   Meaning                 Presentation        Example
+ * ------   -------                 ------------        -------
+ * G        era designator          (Text)              AD
+ * y        year                    (Number)            1996
+ * Y        year (week of year)     (Number)            1997
+ * u        extended year           (Number)            4601
+ * Q        Quarter                 (Text & Number)     Q2 & 02
+ * M        month in year           (Text & Number)     July & 07
+ * d        day in month            (Number)            10
+ * h        hour in am/pm (1~12)    (Number)            12
+ * H        hour in day (0~23)      (Number)            0
+ * m        minute in hour          (Number)            30
+ * s        second in minute        (Number)            55
+ * S        fractional second       (Number)            978
+ * E        day of week             (Text)              Tuesday
+ * e        day of week (local 1~7) (Text & Number)     Tues & 2
+ * D        day in year             (Number)            189
+ * F        day of week in month    (Number)            2 (2nd Wed in July)
+ * w        week in year            (Number)            27
+ * W        week in month           (Number)            2
+ * a        am/pm marker            (Text)              PM
+ * k        hour in day (1~24)      (Number)            24
+ * K        hour in am/pm (0~11)    (Number)            0
+ * z        time zone               (Time)              Pacific Standard Time
+ * Z        time zone (RFC 822)     (Number)            -0800
+ * v        time zone (generic)     (Text)              Pacific Time
+ * V        time zone (abreviation) (Text)              PT
+ * VVVV     time zone (location)    (Text)              United States (Los Angeles)
+ * g        Julian day              (Number)            2451334
+ * A        milliseconds in day     (Number)            69540000
+ * q        stand alone quarter     (Text & Number)     Q2 & 02
+ * L        stand alone month       (Text & Number)     July & 07
+ * c        stand alone day of week (Text & Number)     Tuesday & 2
+ * '        escape for text         (Delimiter)         'Date='
+ * ''       single quote            (Literal)           'o''clock'
+ * \endcode
+ * 
+ * The count of pattern letters determine the format. + *

+ * (Text): 4 or more, use full form, <4, use short or abbreviated form if it + * exists. (e.g., "EEEE" produces "Monday", "EEE" produces "Mon") + *

+ * (Number): the minimum number of digits. Shorter numbers are zero-padded to + * this amount (e.g. if "m" produces "6", "mm" produces "06"). Year is handled + * specially; that is, if the count of 'y' is 2, the Year will be truncated to 2 digits. + * (e.g., if "yyyy" produces "1997", "yy" produces "97".) + * Unlike other fields, fractional seconds are padded on the right with zero. + *

+ * (Text & Number): 3 or over, use text, otherwise use number. (e.g., "M" produces "1", + * "MM" produces "01", "MMM" produces "Jan", and "MMMM" produces "January".) + *

+ * Any characters in the pattern that are not in the ranges of ['a'..'z'] and + * ['A'..'Z'] will be treated as quoted text. For instance, characters + * like ':', '.', ' ', '#' and '@' will appear in the resulting time text + * even they are not embraced within single quotes. + *

+ * A pattern containing any invalid pattern letter will result in a failing + * UErrorCode result during formatting or parsing. + *

+ * Examples using the US locale: + *

+ * \code
+ *    Format Pattern                         Result
+ *    --------------                         -------
+ *    "yyyy.MM.dd G 'at' HH:mm:ss vvvv" ->>  1996.07.10 AD at 15:08:56 Pacific Time
+ *    "EEE, MMM d, ''yy"                ->>  Wed, July 10, '96
+ *    "h:mm a"                          ->>  12:08 PM
+ *    "hh 'o''clock' a, zzzz"           ->>  12 o'clock PM, Pacific Daylight Time
+ *    "K:mm a, vvv"                     ->>  0:00 PM, PT
+ *    "yyyyy.MMMMM.dd GGG hh:mm aaa"    ->>  1996.July.10 AD 12:08 PM
+ * \endcode
+ * 
+ * Code Sample: + *
+ * \code
+ *     UErrorCode success = U_ZERO_ERROR;
+ *     SimpleTimeZone* pdt = new SimpleTimeZone(-8 * 60 * 60 * 1000, "PST");
+ *     pdt->setStartRule( Calendar::APRIL, 1, Calendar::SUNDAY, 2*60*60*1000);
+ *     pdt->setEndRule( Calendar::OCTOBER, -1, Calendar::SUNDAY, 2*60*60*1000);
+ *
+ *     // Format the current time.
+ *     SimpleDateFormat* formatter
+ *         = new SimpleDateFormat ("yyyy.MM.dd G 'at' hh:mm:ss a zzz", success );
+ *     GregorianCalendar cal(success);
+ *     UDate currentTime_1 = cal.getTime(success);
+ *     FieldPosition fp(0);
+ *     UnicodeString dateString;
+ *     formatter->format( currentTime_1, dateString, fp );
+ *     cout << "result: " << dateString << endl;
+ *
+ *     // Parse the previous string back into a Date.
+ *     ParsePosition pp(0);
+ *     UDate currentTime_2 = formatter->parse(dateString, pp );
+ * \endcode
+ * 
+ * In the above example, the time value "currentTime_2" obtained from parsing + * will be equal to currentTime_1. However, they may not be equal if the am/pm + * marker 'a' is left out from the format pattern while the "hour in am/pm" + * pattern symbol is used. This information loss can happen when formatting the + * time in PM. + * + *

+ * When parsing a date string using the abbreviated year pattern ("y" or "yy"), + * SimpleDateFormat must interpret the abbreviated year + * relative to some century. It does this by adjusting dates to be + * within 80 years before and 20 years after the time the SimpleDateFormat + * instance is created. For example, using a pattern of "MM/dd/yy" and a + * SimpleDateFormat instance created on Jan 1, 1997, the string + * "01/11/12" would be interpreted as Jan 11, 2012 while the string "05/04/64" + * would be interpreted as May 4, 1964. + * During parsing, only strings consisting of exactly two digits, as defined by + * Unicode::isDigit(), will be parsed into the default century. + * Any other numeric string, such as a one digit string, a three or more digit + * string, or a two digit string that isn't all digits (for example, "-1"), is + * interpreted literally. So "01/02/3" or "01/02/003" are parsed, using the + * same pattern, as Jan 2, 3 AD. Likewise, "01/02/-3" is parsed as Jan 2, 4 BC. + * + *

+ * If the year pattern has more than two 'y' characters, the year is + * interpreted literally, regardless of the number of digits. So using the + * pattern "MM/dd/yyyy", "01/11/12" parses to Jan 11, 12 A.D. + * + *

+ * When numeric fields abut one another directly, with no intervening delimiter + * characters, they constitute a run of abutting numeric fields. Such runs are + * parsed specially. For example, the format "HHmmss" parses the input text + * "123456" to 12:34:56, parses the input text "12345" to 1:23:45, and fails to + * parse "1234". In other words, the leftmost field of the run is flexible, + * while the others keep a fixed width. If the parse fails anywhere in the run, + * then the leftmost field is shortened by one character, and the entire run is + * parsed again. This is repeated until either the parse succeeds or the + * leftmost field is one character in length. If the parse still fails at that + * point, the parse of the run fails. + * + *

+ * For time zones that have no names, SimpleDateFormat uses strings GMT+hours:minutes or + * GMT-hours:minutes. + *

+ * The calendar defines what is the first day of the week, the first week of the + * year, whether hours are zero based or not (0 vs 12 or 24), and the timezone. + * There is one common number format to handle all the numbers; the digit count + * is handled programmatically according to the pattern. + * + *

User subclasses are not supported. While clients may write + * subclasses, such code will not necessarily work and will not be + * guaranteed to work stably from release to release. + */ +class U_I18N_API SimpleDateFormat: public DateFormat { +public: + /** + * Construct a SimpleDateFormat using the default pattern for the default + * locale. + *

+ * [Note:] Not all locales support SimpleDateFormat; for full generality, + * use the factory methods in the DateFormat class. + * @param status Output param set to success/failure code. + * @stable ICU 2.0 + */ + SimpleDateFormat(UErrorCode& status); + + /** + * Construct a SimpleDateFormat using the given pattern and the default locale. + * The locale is used to obtain the symbols used in formatting (e.g., the + * names of the months), but not to provide the pattern. + *

+ * [Note:] Not all locales support SimpleDateFormat; for full generality, + * use the factory methods in the DateFormat class. + * @param pattern the pattern for the format. + * @param status Output param set to success/failure code. + * @stable ICU 2.0 + */ + SimpleDateFormat(const UnicodeString& pattern, + UErrorCode& status); + + /** + * Construct a SimpleDateFormat using the given pattern, numbering system override, and the default locale. + * The locale is used to obtain the symbols used in formatting (e.g., the + * names of the months), but not to provide the pattern. + *

+ * A numbering system override is a string containing either the name of a known numbering system, + * or a set of field and numbering system pairs that specify which fields are to be formattied with + * the alternate numbering system. For example, to specify that all numeric fields in the specified + * date or time pattern are to be rendered using Thai digits, simply specify the numbering system override + * as "thai". To specify that just the year portion of the date be formatted using Hebrew numbering, + * use the override string "y=hebrew". Numbering system overrides can be combined using a semi-colon + * character in the override string, such as "d=decimal;M=arabic;y=hebrew", etc. + * + *

+ * [Note:] Not all locales support SimpleDateFormat; for full generality, + * use the factory methods in the DateFormat class. + * @param pattern the pattern for the format. + * @param override the override string. + * @param status Output param set to success/failure code. + * @stable ICU 4.2 + */ + SimpleDateFormat(const UnicodeString& pattern, + const UnicodeString& override, + UErrorCode& status); + + /** + * Construct a SimpleDateFormat using the given pattern and locale. + * The locale is used to obtain the symbols used in formatting (e.g., the + * names of the months), but not to provide the pattern. + *

+ * [Note:] Not all locales support SimpleDateFormat; for full generality, + * use the factory methods in the DateFormat class. + * @param pattern the pattern for the format. + * @param locale the given locale. + * @param status Output param set to success/failure code. + * @stable ICU 2.0 + */ + SimpleDateFormat(const UnicodeString& pattern, + const Locale& locale, + UErrorCode& status); + + /** + * Construct a SimpleDateFormat using the given pattern, numbering system override, and locale. + * The locale is used to obtain the symbols used in formatting (e.g., the + * names of the months), but not to provide the pattern. + *

+ * A numbering system override is a string containing either the name of a known numbering system, + * or a set of field and numbering system pairs that specify which fields are to be formattied with + * the alternate numbering system. For example, to specify that all numeric fields in the specified + * date or time pattern are to be rendered using Thai digits, simply specify the numbering system override + * as "thai". To specify that just the year portion of the date be formatted using Hebrew numbering, + * use the override string "y=hebrew". Numbering system overrides can be combined using a semi-colon + * character in the override string, such as "d=decimal;M=arabic;y=hebrew", etc. + *

+ * [Note:] Not all locales support SimpleDateFormat; for full generality, + * use the factory methods in the DateFormat class. + * @param pattern the pattern for the format. + * @param override the numbering system override. + * @param locale the given locale. + * @param status Output param set to success/failure code. + * @stable ICU 4.2 + */ + SimpleDateFormat(const UnicodeString& pattern, + const UnicodeString& override, + const Locale& locale, + UErrorCode& status); + + /** + * Construct a SimpleDateFormat using the given pattern and locale-specific + * symbol data. The formatter takes ownership of the DateFormatSymbols object; + * the caller is no longer responsible for deleting it. + * @param pattern the given pattern for the format. + * @param formatDataToAdopt the symbols to be adopted. + * @param status Output param set to success/faulure code. + * @stable ICU 2.0 + */ + SimpleDateFormat(const UnicodeString& pattern, + DateFormatSymbols* formatDataToAdopt, + UErrorCode& status); + + /** + * Construct a SimpleDateFormat using the given pattern and locale-specific + * symbol data. The DateFormatSymbols object is NOT adopted; the caller + * remains responsible for deleting it. + * @param pattern the given pattern for the format. + * @param formatData the formatting symbols to be use. + * @param status Output param set to success/faulure code. + * @stable ICU 2.0 + */ + SimpleDateFormat(const UnicodeString& pattern, + const DateFormatSymbols& formatData, + UErrorCode& status); + + /** + * Copy constructor. + * @stable ICU 2.0 + */ + SimpleDateFormat(const SimpleDateFormat&); + + /** + * Assignment operator. + * @stable ICU 2.0 + */ + SimpleDateFormat& operator=(const SimpleDateFormat&); + + /** + * Destructor. + * @stable ICU 2.0 + */ + virtual ~SimpleDateFormat(); + + /** + * Clone this Format object polymorphically. The caller owns the result and + * should delete it when done. + * @return A copy of the object. + * @stable ICU 2.0 + */ + virtual Format* clone(void) const; + + /** + * Return true if the given Format objects are semantically equal. Objects + * of different subclasses are considered unequal. + * @param other the object to be compared with. + * @return true if the given Format objects are semantically equal. + * @stable ICU 2.0 + */ + virtual UBool operator==(const Format& other) const; + + + using DateFormat::format; + + /** + * Format a date or time, which is the standard millis since 24:00 GMT, Jan + * 1, 1970. Overrides DateFormat pure virtual method. + *

+ * Example: using the US locale: "yyyy.MM.dd e 'at' HH:mm:ss zzz" ->> + * 1996.07.10 AD at 15:08:56 PDT + * + * @param cal Calendar set to the date and time to be formatted + * into a date/time string. + * @param appendTo Output parameter to receive result. + * Result is appended to existing contents. + * @param pos The formatting position. On input: an alignment field, + * if desired. On output: the offsets of the alignment field. + * @return Reference to 'appendTo' parameter. + * @stable ICU 2.1 + */ + virtual UnicodeString& format( Calendar& cal, + UnicodeString& appendTo, + FieldPosition& pos) const; + + /** + * Format a date or time, which is the standard millis since 24:00 GMT, Jan + * 1, 1970. Overrides DateFormat pure virtual method. + *

+ * Example: using the US locale: "yyyy.MM.dd e 'at' HH:mm:ss zzz" ->> + * 1996.07.10 AD at 15:08:56 PDT + * + * @param cal Calendar set to the date and time to be formatted + * into a date/time string. + * @param appendTo Output parameter to receive result. + * Result is appended to existing contents. + * @param posIter On return, can be used to iterate over positions + * of fields generated by this format call. Field values + * are defined in UDateFormatField. + * @param status Input/output param set to success/failure code. + * @return Reference to 'appendTo' parameter. + * @stable ICU 4.4 + */ + virtual UnicodeString& format( Calendar& cal, + UnicodeString& appendTo, + FieldPositionIterator* posIter, + UErrorCode& status) const; + + /** + * Format a date or time, which is the standard millis since 24:00 GMT, Jan + * 1, 1970. Overrides DateFormat pure virtual method. + *

+ * Example: using the US locale: "yyyy.MM.dd e 'at' HH:mm:ss zzz" ->> + * 1996.07.10 AD at 15:08:56 PDT + * + * @param obj A Formattable containing the date-time value to be formatted + * into a date-time string. If the type of the Formattable + * is a numeric type, it is treated as if it were an + * instance of Date. + * @param appendTo Output parameter to receive result. + * Result is appended to existing contents. + * @param pos The formatting position. On input: an alignment field, + * if desired. On output: the offsets of the alignment field. + * @param status Input/output param set to success/failure code. + * @return Reference to 'appendTo' parameter. + * @stable ICU 2.0 + */ + virtual UnicodeString& format( const Formattable& obj, + UnicodeString& appendTo, + FieldPosition& pos, + UErrorCode& status) const; + + /** + * Format a date or time, which is the standard millis since 24:00 GMT, Jan + * 1, 1970. Overrides DateFormat pure virtual method. + *

+ * Example: using the US locale: "yyyy.MM.dd e 'at' HH:mm:ss zzz" ->> + * 1996.07.10 AD at 15:08:56 PDT + * + * @param obj A Formattable containing the date-time value to be formatted + * into a date-time string. If the type of the Formattable + * is a numeric type, it is treated as if it were an + * instance of Date. + * @param appendTo Output parameter to receive result. + * Result is appended to existing contents. + * @param posIter On return, can be used to iterate over positions + * of fields generated by this format call. Field values + * are defined in UDateFormatField. + * @param status Input/output param set to success/failure code. + * @return Reference to 'appendTo' parameter. + * @stable ICU 4.4 + */ + virtual UnicodeString& format( const Formattable& obj, + UnicodeString& appendTo, + FieldPositionIterator* posIter, + UErrorCode& status) const; + + /** + * Redeclared DateFormat method. + * @param date the Date value to be formatted. + * @param appendTo Output parameter to receive result. + * Result is appended to existing contents. + * @param fieldPosition The formatting position. On input: an alignment field, + * if desired. On output: the offsets of the alignment field. + * @return Reference to 'appendTo' parameter. + * @stable ICU 2.1 + */ + UnicodeString& format(UDate date, + UnicodeString& appendTo, + FieldPosition& fieldPosition) const; + + /** + * Redeclared DateFormat method. + * @param date the Date value to be formatted. + * @param appendTo Output parameter to receive result. + * Result is appended to existing contents. + * @param posIter On return, can be used to iterate over positions + * of fields generated by this format call. Field values + * are defined in UDateFormatField. + * @param status Input/output param set to success/failure code. + * @return Reference to 'appendTo' parameter. + * @stable ICU 4.4 + */ + UnicodeString& format(UDate date, + UnicodeString& appendTo, + FieldPositionIterator* posIter, + UErrorCode& status) const; + + /** + * Redeclared DateFormat method. + * @param obj Object to be formatted. + * @param appendTo Output parameter to receive result. + * Result is appended to existing contents. + * @param status Input/output success/failure code. + * @return Reference to 'appendTo' parameter. + * @stable ICU 2.0 + */ + UnicodeString& format(const Formattable& obj, + UnicodeString& appendTo, + UErrorCode& status) const; + + /** + * Redeclared DateFormat method. + * @param date Date value to be formatted. + * @param appendTo Output parameter to receive result. + * Result is appended to existing contents. + * @return Reference to 'appendTo' parameter. + * @stable ICU 2.0 + */ + UnicodeString& format(UDate date, UnicodeString& appendTo) const; + + /** + * Parse a date/time string beginning at the given parse position. For + * example, a time text "07/10/96 4:5 PM, PDT" will be parsed into a Date + * that is equivalent to Date(837039928046). + *

+ * By default, parsing is lenient: If the input is not in the form used by + * this object's format method but can still be parsed as a date, then the + * parse succeeds. Clients may insist on strict adherence to the format by + * calling setLenient(false). + * + * @param text The date/time string to be parsed + * @param cal a Calendar set to the date and time to be formatted + * into a date/time string. + * @param pos On input, the position at which to start parsing; on + * output, the position at which parsing terminated, or the + * start position if the parse failed. + * @return A valid UDate if the input could be parsed. + * @stable ICU 2.1 + */ + virtual void parse( const UnicodeString& text, + Calendar& cal, + ParsePosition& pos) const; + + /** + * Parse a date/time string starting at the given parse position. For + * example, a time text "07/10/96 4:5 PM, PDT" will be parsed into a Date + * that is equivalent to Date(837039928046). + *

+ * By default, parsing is lenient: If the input is not in the form used by + * this object's format method but can still be parsed as a date, then the + * parse succeeds. Clients may insist on strict adherence to the format by + * calling setLenient(false). + * + * @see DateFormat::setLenient(boolean) + * + * @param text The date/time string to be parsed + * @param pos On input, the position at which to start parsing; on + * output, the position at which parsing terminated, or the + * start position if the parse failed. + * @return A valid UDate if the input could be parsed. + * @stable ICU 2.0 + */ + UDate parse( const UnicodeString& text, + ParsePosition& pos) const; + + + /** + * Parse a date/time string. For example, a time text "07/10/96 4:5 PM, PDT" + * will be parsed into a UDate that is equivalent to Date(837039928046). + * Parsing begins at the beginning of the string and proceeds as far as + * possible. Assuming no parse errors were encountered, this function + * doesn't return any information about how much of the string was consumed + * by the parsing. If you need that information, use the version of + * parse() that takes a ParsePosition. + * + * @param text The date/time string to be parsed + * @param status Filled in with U_ZERO_ERROR if the parse was successful, and with + * an error value if there was a parse error. + * @return A valid UDate if the input could be parsed. + * @stable ICU 2.0 + */ + virtual UDate parse( const UnicodeString& text, + UErrorCode& status) const; + + /** + * Set the start UDate used to interpret two-digit year strings. + * When dates are parsed having 2-digit year strings, they are placed within + * a assumed range of 100 years starting on the two digit start date. For + * example, the string "24-Jan-17" may be in the year 1817, 1917, 2017, or + * some other year. SimpleDateFormat chooses a year so that the resultant + * date is on or after the two digit start date and within 100 years of the + * two digit start date. + *

+ * By default, the two digit start date is set to 80 years before the current + * time at which a SimpleDateFormat object is created. + * @param d start UDate used to interpret two-digit year strings. + * @param status Filled in with U_ZERO_ERROR if the parse was successful, and with + * an error value if there was a parse error. + * @stable ICU 2.0 + */ + virtual void set2DigitYearStart(UDate d, UErrorCode& status); + + /** + * Get the start UDate used to interpret two-digit year strings. + * When dates are parsed having 2-digit year strings, they are placed within + * a assumed range of 100 years starting on the two digit start date. For + * example, the string "24-Jan-17" may be in the year 1817, 1917, 2017, or + * some other year. SimpleDateFormat chooses a year so that the resultant + * date is on or after the two digit start date and within 100 years of the + * two digit start date. + *

+ * By default, the two digit start date is set to 80 years before the current + * time at which a SimpleDateFormat object is created. + * @param status Filled in with U_ZERO_ERROR if the parse was successful, and with + * an error value if there was a parse error. + * @stable ICU 2.0 + */ + UDate get2DigitYearStart(UErrorCode& status) const; + + /** + * Return a pattern string describing this date format. + * @param result Output param to receive the pattern. + * @return A reference to 'result'. + * @stable ICU 2.0 + */ + virtual UnicodeString& toPattern(UnicodeString& result) const; + + /** + * Return a localized pattern string describing this date format. + * In most cases, this will return the same thing as toPattern(), + * but a locale can specify characters to use in pattern descriptions + * in place of the ones described in this class's class documentation. + * (Presumably, letters that would be more mnemonic in that locale's + * language.) This function would produce a pattern using those + * letters. + * + * @param result Receives the localized pattern. + * @param status Output param set to success/failure code on + * exit. If the pattern is invalid, this will be + * set to a failure result. + * @return A reference to 'result'. + * @stable ICU 2.0 + */ + virtual UnicodeString& toLocalizedPattern(UnicodeString& result, + UErrorCode& status) const; + + /** + * Apply the given unlocalized pattern string to this date format. + * (i.e., after this call, this formatter will format dates according to + * the new pattern) + * + * @param pattern The pattern to be applied. + * @stable ICU 2.0 + */ + virtual void applyPattern(const UnicodeString& pattern); + + /** + * Apply the given localized pattern string to this date format. + * (see toLocalizedPattern() for more information on localized patterns.) + * + * @param pattern The localized pattern to be applied. + * @param status Output param set to success/failure code on + * exit. If the pattern is invalid, this will be + * set to a failure result. + * @stable ICU 2.0 + */ + virtual void applyLocalizedPattern(const UnicodeString& pattern, + UErrorCode& status); + + /** + * Gets the date/time formatting symbols (this is an object carrying + * the various strings and other symbols used in formatting: e.g., month + * names and abbreviations, time zone names, AM/PM strings, etc.) + * @return a copy of the date-time formatting data associated + * with this date-time formatter. + * @stable ICU 2.0 + */ + virtual const DateFormatSymbols* getDateFormatSymbols(void) const; + + /** + * Set the date/time formatting symbols. The caller no longer owns the + * DateFormatSymbols object and should not delete it after making this call. + * @param newFormatSymbols the given date-time formatting symbols to copy. + * @stable ICU 2.0 + */ + virtual void adoptDateFormatSymbols(DateFormatSymbols* newFormatSymbols); + + /** + * Set the date/time formatting data. + * @param newFormatSymbols the given date-time formatting symbols to copy. + * @stable ICU 2.0 + */ + virtual void setDateFormatSymbols(const DateFormatSymbols& newFormatSymbols); + + /** + * Return the class ID for this class. This is useful only for comparing to + * a return value from getDynamicClassID(). For example: + *

+     * .   Base* polymorphic_pointer = createPolymorphicObject();
+     * .   if (polymorphic_pointer->getDynamicClassID() ==
+     * .       erived::getStaticClassID()) ...
+     * 
+ * @return The class ID for all objects of this class. + * @stable ICU 2.0 + */ + static UClassID U_EXPORT2 getStaticClassID(void); + + /** + * Returns a unique class ID POLYMORPHICALLY. Pure virtual override. This + * method is to implement a simple version of RTTI, since not all C++ + * compilers support genuine RTTI. Polymorphic operator==() and clone() + * methods call this method. + * + * @return The class ID for this object. All objects of a + * given class have the same class ID. Objects of + * other classes have different class IDs. + * @stable ICU 2.0 + */ + virtual UClassID getDynamicClassID(void) const; + + /** + * Set the calendar to be used by this date format. Initially, the default + * calendar for the specified or default locale is used. The caller should + * not delete the Calendar object after it is adopted by this call. + * Adopting a new calendar will change to the default symbols. + * + * @param calendarToAdopt Calendar object to be adopted. + * @stable ICU 2.0 + */ + virtual void adoptCalendar(Calendar* calendarToAdopt); + + /** + * This is for ICU internal use only. Please do not use. + * Check whether the 'field' is smaller than all the fields covered in + * pattern, return TRUE if it is. The sequence of calendar field, + * from large to small is: ERA, YEAR, MONTH, DATE, AM_PM, HOUR, MINUTE,... + * @param field the calendar field need to check against + * @return TRUE if the 'field' is smaller than all the fields + * covered in pattern. FALSE otherwise. + * @internal ICU 4.0 + */ + UBool isFieldUnitIgnored(UCalendarDateFields field) const; + + + /** + * This is for ICU internal use only. Please do not use. + * Check whether the 'field' is smaller than all the fields covered in + * pattern, return TRUE if it is. The sequence of calendar field, + * from large to small is: ERA, YEAR, MONTH, DATE, AM_PM, HOUR, MINUTE,... + * @param pattern the pattern to check against + * @param field the calendar field need to check against + * @return TRUE if the 'field' is smaller than all the fields + * covered in pattern. FALSE otherwise. + * @internal ICU 4.0 + */ + static UBool isFieldUnitIgnored(const UnicodeString& pattern, + UCalendarDateFields field); + + + + /** + * This is for ICU internal use only. Please do not use. + * Get the locale of this simple date formatter. + * It is used in DateIntervalFormat. + * + * @return locale in this simple date formatter + * @internal ICU 4.0 + */ + const Locale& getSmpFmtLocale(void) const; + + +private: + friend class DateFormat; + + void initializeDefaultCentury(void); + + SimpleDateFormat(); // default constructor not implemented + + /** + * Used by the DateFormat factory methods to construct a SimpleDateFormat. + * @param timeStyle the time style. + * @param dateStyle the date style. + * @param locale the given locale. + * @param status Output param set to success/failure code on + * exit. + */ + SimpleDateFormat(EStyle timeStyle, EStyle dateStyle, const Locale& locale, UErrorCode& status); + + /** + * Construct a SimpleDateFormat for the given locale. If no resource data + * is available, create an object of last resort, using hard-coded strings. + * This is an internal method, called by DateFormat. It should never fail. + * @param locale the given locale. + * @param status Output param set to success/failure code on + * exit. + */ + SimpleDateFormat(const Locale& locale, UErrorCode& status); // Use default pattern + + /** + * Hook called by format(... FieldPosition& ...) and format(...FieldPositionIterator&...) + */ + UnicodeString& _format(Calendar& cal, UnicodeString& appendTo, FieldPositionHandler& handler, + UErrorCode& status) const; + + /** + * Called by format() to format a single field. + * + * @param appendTo Output parameter to receive result. + * Result is appended to existing contents. + * @param ch The format character we encountered in the pattern. + * @param count Number of characters in the current pattern symbol (e.g., + * "yyyy" in the pattern would result in a call to this function + * with ch equal to 'y' and count equal to 4) + * @param handler Records information about field positions. + * @param cal Calendar to use + * @param status Receives a status code, which will be U_ZERO_ERROR if the operation + * succeeds. + */ + void subFormat(UnicodeString &appendTo, + UChar ch, + int32_t count, + FieldPositionHandler& handler, + Calendar& cal, + UErrorCode& status) const; // in case of illegal argument + + /** + * Used by subFormat() to format a numeric value. + * Appends to toAppendTo a string representation of "value" + * having a number of digits between "minDigits" and + * "maxDigits". Uses the DateFormat's NumberFormat. + * + * @param currentNumberFormat + * @param appendTo Output parameter to receive result. + * Formatted number is appended to existing contents. + * @param value Value to format. + * @param minDigits Minimum number of digits the result should have + * @param maxDigits Maximum number of digits the result should have + */ + void zeroPaddingNumber(NumberFormat *currentNumberFormat, + UnicodeString &appendTo, + int32_t value, + int32_t minDigits, + int32_t maxDigits) const; + + /** + * Return true if the given format character, occuring count + * times, represents a numeric field. + */ + static UBool isNumeric(UChar formatChar, int32_t count); + + /** + * initializes fCalendar from parameters. Returns fCalendar as a convenience. + * @param adoptZone Zone to be adopted, or NULL for TimeZone::createDefault(). + * @param locale Locale of the calendar + * @param status Error code + * @return the newly constructed fCalendar + */ + Calendar *initializeCalendar(TimeZone* adoptZone, const Locale& locale, UErrorCode& status); + + /** + * initializes fSymbols from parameters. + * @param locale Locale of the symbols + * @param calendar Alias to Calendar that will be used. + * @param status Error code + */ + void initializeSymbols(const Locale& locale, Calendar* calendar, UErrorCode& status); + + /** + * Called by several of the constructors to load pattern data and formatting symbols + * out of a resource bundle and initialize the locale based on it. + * @param timeStyle The time style, as passed to DateFormat::createDateInstance(). + * @param dateStyle The date style, as passed to DateFormat::createTimeInstance(). + * @param locale The locale to load the patterns from. + * @param status Filled in with an error code if loading the data from the + * resources fails. + */ + void construct(EStyle timeStyle, EStyle dateStyle, const Locale& locale, UErrorCode& status); + + /** + * Called by construct() and the various constructors to set up the SimpleDateFormat's + * Calendar and NumberFormat objects. + * @param locale The locale for which we want a Calendar and a NumberFormat. + * @param status Filled in with an error code if creating either subobject fails. + */ + void initialize(const Locale& locale, UErrorCode& status); + + /** + * Private code-size reduction function used by subParse. + * @param text the time text being parsed. + * @param start where to start parsing. + * @param field the date field being parsed. + * @param stringArray the string array to parsed. + * @param stringArrayCount the size of the array. + * @param cal a Calendar set to the date and time to be formatted + * into a date/time string. + * @return the new start position if matching succeeded; a negative number + * indicating matching failure, otherwise. + */ + int32_t matchString(const UnicodeString& text, int32_t start, UCalendarDateFields field, + const UnicodeString* stringArray, int32_t stringArrayCount, Calendar& cal) const; + + /** + * Private code-size reduction function used by subParse. + * @param text the time text being parsed. + * @param start where to start parsing. + * @param field the date field being parsed. + * @param stringArray the string array to parsed. + * @param stringArrayCount the size of the array. + * @param cal a Calendar set to the date and time to be formatted + * into a date/time string. + * @return the new start position if matching succeeded; a negative number + * indicating matching failure, otherwise. + */ + int32_t matchQuarterString(const UnicodeString& text, int32_t start, UCalendarDateFields field, + const UnicodeString* stringArray, int32_t stringArrayCount, Calendar& cal) const; + + /** + * Private function used by subParse to match literal pattern text. + * + * @param pattern the pattern string + * @param patternOffset the starting offset into the pattern text. On + * outupt will be set the offset of the first non-literal character in the pattern + * @param text the text being parsed + * @param textOffset the starting offset into the text. On output + * will be set to the offset of the character after the match + * @param lenient TRUE if the parse is lenient, FALSE otherwise. + * + * @return TRUE if the literal text could be matched, FALSE otherwise. + */ + static UBool matchLiterals(const UnicodeString &pattern, int32_t &patternOffset, + const UnicodeString &text, int32_t &textOffset, UBool lenient); + + /** + * Private member function that converts the parsed date strings into + * timeFields. Returns -start (for ParsePosition) if failed. + * @param text the time text to be parsed. + * @param start where to start parsing. + * @param ch the pattern character for the date field text to be parsed. + * @param count the count of a pattern character. + * @param obeyCount if true then the count is strictly obeyed. + * @param allowNegative + * @param ambiguousYear If true then the two-digit year == the default start year. + * @param saveHebrewMonth Used to hang onto month until year is known. + * @param cal a Calendar set to the date and time to be formatted + * into a date/time string. + * @param patLoc + * @return the new start position if matching succeeded; a negative number + * indicating matching failure, otherwise. + */ + int32_t subParse(const UnicodeString& text, int32_t& start, UChar ch, int32_t count, + UBool obeyCount, UBool allowNegative, UBool ambiguousYear[], int32_t& saveHebrewMonth, Calendar& cal, + int32_t patLoc) const; + + void parseInt(const UnicodeString& text, + Formattable& number, + ParsePosition& pos, + UBool allowNegative, + NumberFormat *fmt) const; + + void parseInt(const UnicodeString& text, + Formattable& number, + int32_t maxDigits, + ParsePosition& pos, + UBool allowNegative, + NumberFormat *fmt) const; + + int32_t checkIntSuffix(const UnicodeString& text, int32_t start, + int32_t patLoc, UBool isNegative) const; + + /** + * Translate a pattern, mapping each character in the from string to the + * corresponding character in the to string. Return an error if the original + * pattern contains an unmapped character, or if a quote is unmatched. + * Quoted (single quotes only) material is not translated. + * @param originalPattern the original pattern. + * @param translatedPattern Output param to receive the translited pattern. + * @param from the characters to be translited from. + * @param to the characters to be translited to. + * @param status Receives a status code, which will be U_ZERO_ERROR + * if the operation succeeds. + */ + static void translatePattern(const UnicodeString& originalPattern, + UnicodeString& translatedPattern, + const UnicodeString& from, + const UnicodeString& to, + UErrorCode& status); + + /** + * Sets the starting date of the 100-year window that dates with 2-digit years + * are considered to fall within. + * @param startDate the start date + * @param status Receives a status code, which will be U_ZERO_ERROR + * if the operation succeeds. + */ + void parseAmbiguousDatesAsAfter(UDate startDate, UErrorCode& status); + + /** + * Return the length matched by the given affix, or -1 if none. + * Runs of white space in the affix, match runs of white space in + * the input. + * @param affix pattern string, taken as a literal + * @param input input text + * @param pos offset into input at which to begin matching + * @return length of input that matches, or -1 if match failure + */ + int32_t compareSimpleAffix(const UnicodeString& affix, + const UnicodeString& input, + int32_t pos) const; + + /** + * Skip over a run of zero or more Pattern_White_Space characters at + * pos in text. + */ + int32_t skipPatternWhiteSpace(const UnicodeString& text, int32_t pos) const; + + /** + * Skip over a run of zero or more isUWhiteSpace() characters at pos + * in text. + */ + int32_t skipUWhiteSpace(const UnicodeString& text, int32_t pos) const; + + /** + * Private methods for formatting/parsing GMT string + */ + void appendGMT(NumberFormat *currentNumberFormat,UnicodeString &appendTo, Calendar& cal, UErrorCode& status) const; + void formatGMTDefault(NumberFormat *currentNumberFormat,UnicodeString &appendTo, int32_t offset) const; + int32_t parseGMT(const UnicodeString &text, ParsePosition &pos) const; + int32_t parseGMTDefault(const UnicodeString &text, ParsePosition &pos) const; + UBool isDefaultGMTFormat() const; + + void formatRFC822TZ(UnicodeString &appendTo, int32_t offset) const; + + /** + * Initialize MessageFormat instances used for GMT formatting/parsing + */ + void initGMTFormatters(UErrorCode &status); + + /** + * Initialize NumberFormat instances used for numbering system overrides. + */ + void initNumberFormatters(const Locale &locale,UErrorCode &status); + + /** + * Get the numbering system to be used for a particular field. + */ + NumberFormat * getNumberFormatByIndex(UDateFormatField index) const; + + /** + * Parse the given override string and set up structures for number formats + */ + void processOverrideString(const Locale &locale, const UnicodeString &str, int8_t type, UErrorCode &status); + + /** + * Used to map pattern characters to Calendar field identifiers. + */ + static const UCalendarDateFields fgPatternIndexToCalendarField[]; + + /** + * Map index into pattern character string to DateFormat field number + */ + static const UDateFormatField fgPatternIndexToDateFormatField[]; + + /** + * Lazy TimeZoneFormat instantiation, semantically const + */ + TimeZoneFormat *tzFormat() const; + + /** + * Used to map Calendar field to field level. + * The larger the level, the smaller the field unit. + * For example, UCAL_ERA level is 0, UCAL_YEAR level is 10, + * UCAL_MONTH level is 20. + */ + static const int32_t fgCalendarFieldToLevel[]; + static const int32_t fgPatternCharToLevel[]; + + /** + * The formatting pattern for this formatter. + */ + UnicodeString fPattern; + + /** + * The numbering system override for dates. + */ + UnicodeString fDateOverride; + + /** + * The numbering system override for times. + */ + UnicodeString fTimeOverride; + + + /** + * The original locale used (for reloading symbols) + */ + Locale fLocale; + + /** + * A pointer to an object containing the strings to use in formatting (e.g., + * month and day names, AM and PM strings, time zone names, etc.) + */ + DateFormatSymbols* fSymbols; // Owned + + /** + * The time zone formatter + */ + TimeZoneFormat* fTimeZoneFormat; + + /** + * If dates have ambiguous years, we map them into the century starting + * at defaultCenturyStart, which may be any date. If defaultCenturyStart is + * set to SYSTEM_DEFAULT_CENTURY, which it is by default, then the system + * values are used. The instance values defaultCenturyStart and + * defaultCenturyStartYear are only used if explicitly set by the user + * through the API method parseAmbiguousDatesAsAfter(). + */ + UDate fDefaultCenturyStart; + + /** + * See documentation for defaultCenturyStart. + */ + /*transient*/ int32_t fDefaultCenturyStartYear; + + enum ParsedTZType { + TZTYPE_UNK, + TZTYPE_STD, + TZTYPE_DST + }; + + ParsedTZType tztype; // here to avoid api change + + typedef struct NSOverride { + NumberFormat *nf; + int32_t hash; + NSOverride *next; + } NSOverride; + + /* + * MessageFormat instances used for localized GMT format + */ + enum { + kGMTNegativeHMS = 0, + kGMTNegativeHM, + kGMTPositiveHMS, + kGMTPositiveHM, + + kNumGMTFormatters + }; + enum { + kGMTNegativeHMSMinLenIdx = 0, + kGMTPositiveHMSMinLenIdx, + + kNumGMTFormatMinLengths + }; + + MessageFormat **fGMTFormatters; + // If a GMT hour format has a second field, we need to make sure + // the length of input localized GMT string must match the expected + // length. Otherwise, sub DateForamt handling offset format may + // unexpectedly success parsing input GMT string without second field. + // See #6880 about this issue. + // TODO: SimpleDateFormat should provide an option to invalidate + // + int32_t fGMTFormatHmsMinLen[kNumGMTFormatMinLengths]; + + NumberFormat **fNumberFormatters; + + NSOverride *fOverrideList; + + UBool fHaveDefaultCentury; +}; + +inline UDate +SimpleDateFormat::get2DigitYearStart(UErrorCode& /*status*/) const +{ + return fDefaultCenturyStart; +} + +inline UnicodeString& +SimpleDateFormat::format(const Formattable& obj, + UnicodeString& appendTo, + UErrorCode& status) const { + // Don't use Format:: - use immediate base class only, + // in case immediate base modifies behavior later. + return DateFormat::format(obj, appendTo, status); +} + +inline UnicodeString& +SimpleDateFormat::format(const Formattable& obj, + UnicodeString& appendTo, + FieldPosition& pos, + UErrorCode& status) const +{ + // Don't use Format:: - use immediate base class only, + // in case immediate base modifies behavior later. + return DateFormat::format(obj, appendTo, pos, status); +} + +inline UnicodeString& +SimpleDateFormat::format(const Formattable& obj, + UnicodeString& appendTo, + FieldPositionIterator* posIter, + UErrorCode& status) const +{ + // Don't use Format:: - use immediate base class only, + // in case immediate base modifies behavior later. + return DateFormat::format(obj, appendTo, posIter, status); +} + +inline UnicodeString& +SimpleDateFormat::format(UDate date, + UnicodeString& appendTo, + FieldPosition& fieldPosition) const { + // Don't use Format:: - use immediate base class only, + // in case immediate base modifies behavior later. + return DateFormat::format(date, appendTo, fieldPosition); +} + +inline UnicodeString& +SimpleDateFormat::format(UDate date, + UnicodeString& appendTo, + FieldPositionIterator* posIter, + UErrorCode& status) const { + // Don't use Format:: - use immediate base class only, + // in case immediate base modifies behavior later. + return DateFormat::format(date, appendTo, posIter, status); +} + +inline UnicodeString& +SimpleDateFormat::format(UDate date, UnicodeString& appendTo) const { + return DateFormat::format(date, appendTo); +} + +U_NAMESPACE_END + +#endif /* #if !UCONFIG_NO_FORMATTING */ + +#endif // _SMPDTFMT +//eof diff --git a/deps/prebuilt/include/icu/unicode/udat.h b/deps/prebuilt/include/icu/unicode/udat.h new file mode 100644 index 0000000000..d480c7da51 --- /dev/null +++ b/deps/prebuilt/include/icu/unicode/udat.h @@ -0,0 +1,997 @@ +/* + ******************************************************************************* + * Copyright (C) 1996-2010, International Business Machines + * Corporation and others. All Rights Reserved. + ******************************************************************************* +*/ + +#ifndef UDAT_H +#define UDAT_H + +#include "unicode/utypes.h" + +#if !UCONFIG_NO_FORMATTING + +#include "unicode/localpointer.h" +#include "unicode/ucal.h" +#include "unicode/unum.h" +/** + * \file + * \brief C API: DateFormat + * + *

Date Format C API

+ * + * Date Format C API consists of functions that convert dates and + * times from their internal representations to textual form and back again in a + * language-independent manner. Converting from the internal representation (milliseconds + * since midnight, January 1, 1970) to text is known as "formatting," and converting + * from text to millis is known as "parsing." We currently define only one concrete + * structure UDateFormat, which can handle pretty much all normal + * date formatting and parsing actions. + *

+ * Date Format helps you to format and parse dates for any locale. Your code can + * be completely independent of the locale conventions for months, days of the + * week, or even the calendar format: lunar vs. solar. + *

+ * To format a date for the current Locale with default time and date style, + * use one of the static factory methods: + *

+ * \code
+ *  UErrorCode status = U_ZERO_ERROR;
+ *  UChar *myString;
+ *  int32_t myStrlen = 0;
+ *  UDateFormat* dfmt = udat_open(UDAT_DEFAULT, UDAT_DEFAULT, NULL, NULL, -1, NULL, -1, &status);
+ *  myStrlen = udat_format(dfmt, myDate, NULL, myStrlen, NULL, &status);
+ *  if (status==U_BUFFER_OVERFLOW_ERROR){
+ *      status=U_ZERO_ERROR;
+ *      myString=(UChar*)malloc(sizeof(UChar) * (myStrlen+1) );
+ *      udat_format(dfmt, myDate, myString, myStrlen+1, NULL, &status);
+ *  }
+ * \endcode
+ * 
+ * If you are formatting multiple numbers, it is more efficient to get the + * format and use it multiple times so that the system doesn't have to fetch the + * information about the local language and country conventions multiple times. + *
+ * \code
+ *  UErrorCode status = U_ZERO_ERROR;
+ *  int32_t i, myStrlen = 0;
+ *  UChar* myString;
+ *  char buffer[1024];
+ *  UDate myDateArr[] = { 0.0, 100000000.0, 2000000000.0 }; // test values
+ *  UDateFormat* df = udat_open(UDAT_DEFAULT, UDAT_DEFAULT, NULL, NULL, -1, NULL, 0, &status);
+ *  for (i = 0; i < 3; i++) {
+ *      myStrlen = udat_format(df, myDateArr[i], NULL, myStrlen, NULL, &status);
+ *      if(status == U_BUFFER_OVERFLOW_ERROR){
+ *          status = U_ZERO_ERROR;
+ *          myString = (UChar*)malloc(sizeof(UChar) * (myStrlen+1) );
+ *          udat_format(df, myDateArr[i], myString, myStrlen+1, NULL, &status);
+ *          printf("%s\n", u_austrcpy(buffer, myString) );
+ *          free(myString);
+ *      }
+ *  }
+ * \endcode
+ * 
+ * To get specific fields of a date, you can use UFieldPosition to + * get specific fields. + *
+ * \code
+ *  UErrorCode status = U_ZERO_ERROR;
+ *  UFieldPosition pos;
+ *  UChar *myString;
+ *  int32_t myStrlen = 0;
+ *  char buffer[1024];
+ *
+ *  pos.field = 1;  // Same as the DateFormat::EField enum
+ *  UDateFormat* dfmt = udat_open(UDAT_DEFAULT, UDAT_DEFAULT, NULL, -1, NULL, 0, &status);
+ *  myStrlen = udat_format(dfmt, myDate, NULL, myStrlen, &pos, &status);
+ *  if (status==U_BUFFER_OVERFLOW_ERROR){
+ *      status=U_ZERO_ERROR;
+ *      myString=(UChar*)malloc(sizeof(UChar) * (myStrlen+1) );
+ *      udat_format(dfmt, myDate, myString, myStrlen+1, &pos, &status);
+ *  }
+ *  printf("date format: %s\n", u_austrcpy(buffer, myString));
+ *  buffer[pos.endIndex] = 0;   // NULL terminate the string.
+ *  printf("UFieldPosition position equals %s\n", &buffer[pos.beginIndex]);
+ * \endcode
+ * 
+ * To format a date for a different Locale, specify it in the call to + * udat_open() + *
+ * \code
+ *        UDateFormat* df = udat_open(UDAT_SHORT, UDAT_SHORT, "fr_FR", NULL, -1, NULL, 0, &status);
+ * \endcode
+ * 
+ * You can use a DateFormat API udat_parse() to parse. + *
+ * \code
+ *  UErrorCode status = U_ZERO_ERROR;
+ *  int32_t parsepos=0;
+ *  UDate myDate = udat_parse(df, myString, u_strlen(myString), &parsepos, &status);
+ * \endcode
+ * 
+ * You can pass in different options for the arguments for date and time style + * to control the length of the result; from SHORT to MEDIUM to LONG to FULL. + * The exact result depends on the locale, but generally: + * see UDateFormatStyle for more details + *
    + *
  • UDAT_SHORT is completely numeric, such as 12/13/52 or 3:30pm + *
  • UDAT_MEDIUM is longer, such as Jan 12, 1952 + *
  • UDAT_LONG is longer, such as January 12, 1952 or 3:30:32pm + *
  • UDAT_FULL is pretty completely specified, such as + * Tuesday, April 12, 1952 AD or 3:30:42pm PST. + *
+ * You can also set the time zone on the format if you wish. + *

+ * You can also use forms of the parse and format methods with Parse Position and + * UFieldPosition to allow you to + *

    + *
  • Progressively parse through pieces of a string. + *
  • Align any particular field, or find out where it is for selection + * on the screen. + *
+ */ + +/** A date formatter. + * For usage in C programs. + * @stable ICU 2.6 + */ +typedef void* UDateFormat; + +/** The possible date/time format styles + * @stable ICU 2.6 + */ +typedef enum UDateFormatStyle { + /** Full style */ + UDAT_FULL, + /** Long style */ + UDAT_LONG, + /** Medium style */ + UDAT_MEDIUM, + /** Short style */ + UDAT_SHORT, + /** Default style */ + UDAT_DEFAULT = UDAT_MEDIUM, + + /** Bitfield for relative date */ + UDAT_RELATIVE = (1 << 7), + + UDAT_FULL_RELATIVE = UDAT_FULL | UDAT_RELATIVE, + + UDAT_LONG_RELATIVE = UDAT_LONG | UDAT_RELATIVE, + + UDAT_MEDIUM_RELATIVE = UDAT_MEDIUM | UDAT_RELATIVE, + + UDAT_SHORT_RELATIVE = UDAT_SHORT | UDAT_RELATIVE, + + + /** No style */ + UDAT_NONE = -1, + /** for internal API use only */ + UDAT_IGNORE = -2 + +} UDateFormatStyle; + + +/** + * @{ + * Below are a set of pre-defined skeletons. + * + *

+ * A skeleton + *

    + *
  1. + * only keeps the field pattern letter and ignores all other parts + * in a pattern, such as space, punctuations, and string literals. + *
  2. + *
  3. + * hides the order of fields. + *
  4. + *
  5. + * might hide a field's pattern letter length. + * + * For those non-digit calendar fields, the pattern letter length is + * important, such as MMM, MMMM, and MMMMM; EEE and EEEE, + * and the field's pattern letter length is honored. + * + * For the digit calendar fields, such as M or MM, d or dd, yy or yyyy, + * the field pattern length is ignored and the best match, which is defined + * in date time patterns, will be returned without honor the field pattern + * letter length in skeleton. + *
  6. + *
+ * + * @stable ICU 4.0 + */ + +#define UDAT_MINUTE_SECOND "ms" +#define UDAT_HOUR24_MINUTE "Hm" +#define UDAT_HOUR24_MINUTE_SECOND "Hms" +#define UDAT_HOUR_MINUTE_SECOND "hms" +#define UDAT_STANDALONE_MONTH "LLLL" +#define UDAT_ABBR_STANDALONE_MONTH "LLL" +#define UDAT_YEAR_QUARTER "yQQQ" +#define UDAT_YEAR_ABBR_QUARTER "yQ" + +/** @} */ + +/** + * @{ + * Below are a set of pre-defined skeletons that + * have pre-defined interval patterns in resource files. + * Users are encouraged to use them in date interval format factory methods. + * + * @stable ICU 4.0 + */ +#define UDAT_HOUR_MINUTE "hm" +#define UDAT_YEAR "y" +#define UDAT_DAY "d" +#define UDAT_NUM_MONTH_WEEKDAY_DAY "MEd" +#define UDAT_YEAR_NUM_MONTH "yM" +#define UDAT_NUM_MONTH_DAY "Md" +#define UDAT_YEAR_NUM_MONTH_WEEKDAY_DAY "yMEd" +#define UDAT_ABBR_MONTH_WEEKDAY_DAY "MMMEd" +#define UDAT_YEAR_MONTH "yMMMM" +#define UDAT_YEAR_ABBR_MONTH "yMMM" +#define UDAT_MONTH_DAY "MMMMd" +#define UDAT_ABBR_MONTH_DAY "MMMd" +#define UDAT_MONTH_WEEKDAY_DAY "MMMMEEEEd" +#define UDAT_YEAR_ABBR_MONTH_WEEKDAY_DAY "yMMMEd" +#define UDAT_YEAR_MONTH_WEEKDAY_DAY "yMMMMEEEEd" +#define UDAT_YEAR_MONTH_DAY "yMMMMd" +#define UDAT_YEAR_ABBR_MONTH_DAY "yMMMd" +#define UDAT_YEAR_NUM_MONTH_DAY "yMd" +#define UDAT_NUM_MONTH "M" +#define UDAT_ABBR_MONTH "MMM" +#define UDAT_MONTH "MMMM" +#define UDAT_HOUR_MINUTE_GENERIC_TZ "hmv" +#define UDAT_HOUR_MINUTE_TZ "hmz" +#define UDAT_HOUR "h" +#define UDAT_HOUR_GENERIC_TZ "hv" +#define UDAT_HOUR_TZ "hz" + +/** @} */ + + +/** + * FieldPosition and UFieldPosition selectors for format fields + * defined by DateFormat and UDateFormat. + * @stable ICU 3.0 + */ +typedef enum UDateFormatField { + /** + * FieldPosition and UFieldPosition selector for 'G' field alignment, + * corresponding to the UCAL_ERA field. + * @stable ICU 3.0 + */ + UDAT_ERA_FIELD = 0, + + /** + * FieldPosition and UFieldPosition selector for 'y' field alignment, + * corresponding to the UCAL_YEAR field. + * @stable ICU 3.0 + */ + UDAT_YEAR_FIELD = 1, + + /** + * FieldPosition and UFieldPosition selector for 'M' field alignment, + * corresponding to the UCAL_MONTH field. + * @stable ICU 3.0 + */ + UDAT_MONTH_FIELD = 2, + + /** + * FieldPosition and UFieldPosition selector for 'd' field alignment, + * corresponding to the UCAL_DATE field. + * @stable ICU 3.0 + */ + UDAT_DATE_FIELD = 3, + + /** + * FieldPosition and UFieldPosition selector for 'k' field alignment, + * corresponding to the UCAL_HOUR_OF_DAY field. + * UDAT_HOUR_OF_DAY1_FIELD is used for the one-based 24-hour clock. + * For example, 23:59 + 01:00 results in 24:59. + * @stable ICU 3.0 + */ + UDAT_HOUR_OF_DAY1_FIELD = 4, + + /** + * FieldPosition and UFieldPosition selector for 'H' field alignment, + * corresponding to the UCAL_HOUR_OF_DAY field. + * UDAT_HOUR_OF_DAY0_FIELD is used for the zero-based 24-hour clock. + * For example, 23:59 + 01:00 results in 00:59. + * @stable ICU 3.0 + */ + UDAT_HOUR_OF_DAY0_FIELD = 5, + + /** + * FieldPosition and UFieldPosition selector for 'm' field alignment, + * corresponding to the UCAL_MINUTE field. + * @stable ICU 3.0 + */ + UDAT_MINUTE_FIELD = 6, + + /** + * FieldPosition and UFieldPosition selector for 's' field alignment, + * corresponding to the UCAL_SECOND field. + * @stable ICU 3.0 + */ + UDAT_SECOND_FIELD = 7, + + /** + * FieldPosition and UFieldPosition selector for 'S' field alignment, + * corresponding to the UCAL_MILLISECOND field. + * @stable ICU 3.0 + */ + UDAT_FRACTIONAL_SECOND_FIELD = 8, + + /** + * FieldPosition and UFieldPosition selector for 'E' field alignment, + * corresponding to the UCAL_DAY_OF_WEEK field. + * @stable ICU 3.0 + */ + UDAT_DAY_OF_WEEK_FIELD = 9, + + /** + * FieldPosition and UFieldPosition selector for 'D' field alignment, + * corresponding to the UCAL_DAY_OF_YEAR field. + * @stable ICU 3.0 + */ + UDAT_DAY_OF_YEAR_FIELD = 10, + + /** + * FieldPosition and UFieldPosition selector for 'F' field alignment, + * corresponding to the UCAL_DAY_OF_WEEK_IN_MONTH field. + * @stable ICU 3.0 + */ + UDAT_DAY_OF_WEEK_IN_MONTH_FIELD = 11, + + /** + * FieldPosition and UFieldPosition selector for 'w' field alignment, + * corresponding to the UCAL_WEEK_OF_YEAR field. + * @stable ICU 3.0 + */ + UDAT_WEEK_OF_YEAR_FIELD = 12, + + /** + * FieldPosition and UFieldPosition selector for 'W' field alignment, + * corresponding to the UCAL_WEEK_OF_MONTH field. + * @stable ICU 3.0 + */ + UDAT_WEEK_OF_MONTH_FIELD = 13, + + /** + * FieldPosition and UFieldPosition selector for 'a' field alignment, + * corresponding to the UCAL_AM_PM field. + * @stable ICU 3.0 + */ + UDAT_AM_PM_FIELD = 14, + + /** + * FieldPosition and UFieldPosition selector for 'h' field alignment, + * corresponding to the UCAL_HOUR field. + * UDAT_HOUR1_FIELD is used for the one-based 12-hour clock. + * For example, 11:30 PM + 1 hour results in 12:30 AM. + * @stable ICU 3.0 + */ + UDAT_HOUR1_FIELD = 15, + + /** + * FieldPosition and UFieldPosition selector for 'K' field alignment, + * corresponding to the UCAL_HOUR field. + * UDAT_HOUR0_FIELD is used for the zero-based 12-hour clock. + * For example, 11:30 PM + 1 hour results in 00:30 AM. + * @stable ICU 3.0 + */ + UDAT_HOUR0_FIELD = 16, + + /** + * FieldPosition and UFieldPosition selector for 'z' field alignment, + * corresponding to the UCAL_ZONE_OFFSET and + * UCAL_DST_OFFSET fields. + * @stable ICU 3.0 + */ + UDAT_TIMEZONE_FIELD = 17, + + /** + * FieldPosition and UFieldPosition selector for 'Y' field alignment, + * corresponding to the UCAL_YEAR_WOY field. + * @stable ICU 3.0 + */ + UDAT_YEAR_WOY_FIELD = 18, + + /** + * FieldPosition and UFieldPosition selector for 'e' field alignment, + * corresponding to the UCAL_DOW_LOCAL field. + * @stable ICU 3.0 + */ + UDAT_DOW_LOCAL_FIELD = 19, + + /** + * FieldPosition and UFieldPosition selector for 'u' field alignment, + * corresponding to the UCAL_EXTENDED_YEAR field. + * @stable ICU 3.0 + */ + UDAT_EXTENDED_YEAR_FIELD = 20, + + /** + * FieldPosition and UFieldPosition selector for 'g' field alignment, + * corresponding to the UCAL_JULIAN_DAY field. + * @stable ICU 3.0 + */ + UDAT_JULIAN_DAY_FIELD = 21, + + /** + * FieldPosition and UFieldPosition selector for 'A' field alignment, + * corresponding to the UCAL_MILLISECONDS_IN_DAY field. + * @stable ICU 3.0 + */ + UDAT_MILLISECONDS_IN_DAY_FIELD = 22, + + /** + * FieldPosition and UFieldPosition selector for 'Z' field alignment, + * corresponding to the UCAL_ZONE_OFFSET and + * UCAL_DST_OFFSET fields. + * @stable ICU 3.0 + */ + UDAT_TIMEZONE_RFC_FIELD = 23, + + /** + * FieldPosition and UFieldPosition selector for 'v' field alignment, + * corresponding to the UCAL_ZONE_OFFSET field. + * @stable ICU 3.4 + */ + UDAT_TIMEZONE_GENERIC_FIELD = 24, + /** + * FieldPosition selector for 'c' field alignment, + * corresponding to the {@link #UCAL_DOW_LOCAL} field. + * This displays the stand alone day name, if available. + * @stable ICU 3.4 + */ + UDAT_STANDALONE_DAY_FIELD = 25, + + /** + * FieldPosition selector for 'L' field alignment, + * corresponding to the {@link #UCAL_MONTH} field. + * This displays the stand alone month name, if available. + * @stable ICU 3.4 + */ + UDAT_STANDALONE_MONTH_FIELD = 26, + + /** + * FieldPosition selector for "Q" field alignment, + * corresponding to quarters. This is implemented + * using the {@link #UCAL_MONTH} field. This + * displays the quarter. + * @stable ICU 3.6 + */ + UDAT_QUARTER_FIELD = 27, + + /** + * FieldPosition selector for the "q" field alignment, + * corresponding to stand-alone quarters. This is + * implemented using the {@link #UCAL_MONTH} field. + * This displays the stand-alone quarter. + * @stable ICU 3.6 + */ + UDAT_STANDALONE_QUARTER_FIELD = 28, + + /** + * FieldPosition and UFieldPosition selector for 'V' field alignment, + * corresponding to the UCAL_ZONE_OFFSET field. + * @stable ICU 3.8 + */ + UDAT_TIMEZONE_SPECIAL_FIELD = 29, + + /** + * Number of FieldPosition and UFieldPosition selectors for + * DateFormat and UDateFormat. + * Valid selectors range from 0 to UDAT_FIELD_COUNT-1. + * This value is subject to change if new fields are defined + * in the future. + * @stable ICU 3.0 + */ + UDAT_FIELD_COUNT = 30 + +} UDateFormatField; + + +/** + * Maps from a UDateFormatField to the corresponding UCalendarDateFields. + * Note: since the mapping is many-to-one, there is no inverse mapping. + * @param field the UDateFormatField. + * @return the UCalendarDateField. This will be UCAL_FIELD_COUNT in case + * of error (e.g., the input field is UDAT_FIELD_COUNT). + * @stable ICU 4.4 + */ +U_STABLE UCalendarDateFields U_EXPORT2 +udat_toCalendarDateField(UDateFormatField field); + + +/** + * Open a new UDateFormat for formatting and parsing dates and times. + * A UDateFormat may be used to format dates in calls to {@link #udat_format }, + * and to parse dates in calls to {@link #udat_parse }. + * @param timeStyle The style used to format times; one of UDAT_FULL, UDAT_LONG, + * UDAT_MEDIUM, UDAT_SHORT, UDAT_DEFAULT, or UDAT_NONE (relative time styles + * are not currently supported) + * @param dateStyle The style used to format dates; one of UDAT_FULL, UDAT_LONG, + * UDAT_MEDIUM, UDAT_SHORT, UDAT_DEFAULT, UDAT_FULL_RELATIVE, UDAT_LONG_RELATIVE, + * UDAT_MEDIUM_RELATIVE, UDAT_SHORT_RELATIVE, or UDAT_NONE + * @param locale The locale specifying the formatting conventions + * @param tzID A timezone ID specifying the timezone to use. If 0, use + * the default timezone. + * @param tzIDLength The length of tzID, or -1 if null-terminated. + * @param pattern A pattern specifying the format to use. + * @param patternLength The number of characters in the pattern, or -1 if null-terminated. + * @param status A pointer to an UErrorCode to receive any errors + * @return A pointer to a UDateFormat to use for formatting dates and times, or 0 if + * an error occurred. + * @stable ICU 2.0 + */ +U_STABLE UDateFormat* U_EXPORT2 +udat_open(UDateFormatStyle timeStyle, + UDateFormatStyle dateStyle, + const char *locale, + const UChar *tzID, + int32_t tzIDLength, + const UChar *pattern, + int32_t patternLength, + UErrorCode *status); + + +/** +* Close a UDateFormat. +* Once closed, a UDateFormat may no longer be used. +* @param format The formatter to close. +* @stable ICU 2.0 +*/ +U_STABLE void U_EXPORT2 +udat_close(UDateFormat* format); + +#if U_SHOW_CPLUSPLUS_API + +U_NAMESPACE_BEGIN + +/** + * \class LocalUDateFormatPointer + * "Smart pointer" class, closes a UDateFormat via udat_close(). + * For most methods see the LocalPointerBase base class. + * + * @see LocalPointerBase + * @see LocalPointer + * @stable ICU 4.4 + */ +U_DEFINE_LOCAL_OPEN_POINTER(LocalUDateFormatPointer, UDateFormat, udat_close); + +U_NAMESPACE_END + +#endif + +/** + * Open a copy of a UDateFormat. + * This function performs a deep copy. + * @param fmt The format to copy + * @param status A pointer to an UErrorCode to receive any errors. + * @return A pointer to a UDateFormat identical to fmt. + * @stable ICU 2.0 + */ +U_STABLE UDateFormat* U_EXPORT2 +udat_clone(const UDateFormat *fmt, + UErrorCode *status); + +/** +* Format a date using an UDateFormat. +* The date will be formatted using the conventions specified in {@link #udat_open } +* @param format The formatter to use +* @param dateToFormat The date to format +* @param result A pointer to a buffer to receive the formatted number. +* @param resultLength The maximum size of result. +* @param position A pointer to a UFieldPosition. On input, position->field +* is read. On output, position->beginIndex and position->endIndex indicate +* the beginning and ending indices of field number position->field, if such +* a field exists. This parameter may be NULL, in which case no field +* position data is returned. +* @param status A pointer to an UErrorCode to receive any errors +* @return The total buffer size needed; if greater than resultLength, the output was truncated. +* @see udat_parse +* @see UFieldPosition +* @stable ICU 2.0 +*/ +U_STABLE int32_t U_EXPORT2 +udat_format( const UDateFormat* format, + UDate dateToFormat, + UChar* result, + int32_t resultLength, + UFieldPosition* position, + UErrorCode* status); + +/** +* Parse a string into an date/time using a UDateFormat. +* The date will be parsed using the conventions specified in {@link #udat_open } +* @param format The formatter to use. +* @param text The text to parse. +* @param textLength The length of text, or -1 if null-terminated. +* @param parsePos If not 0, on input a pointer to an integer specifying the offset at which +* to begin parsing. If not 0, on output the offset at which parsing ended. +* @param status A pointer to an UErrorCode to receive any errors +* @return The value of the parsed date/time +* @see udat_format +* @stable ICU 2.0 +*/ +U_STABLE UDate U_EXPORT2 +udat_parse( const UDateFormat* format, + const UChar* text, + int32_t textLength, + int32_t *parsePos, + UErrorCode *status); + +/** +* Parse a string into an date/time using a UDateFormat. +* The date will be parsed using the conventions specified in {@link #udat_open } +* @param format The formatter to use. +* @param calendar The calendar in which to store the parsed data. +* @param text The text to parse. +* @param textLength The length of text, or -1 if null-terminated. +* @param parsePos If not 0, on input a pointer to an integer specifying the offset at which +* to begin parsing. If not 0, on output the offset at which parsing ended. +* @param status A pointer to an UErrorCode to receive any errors +* @see udat_format +* @stable ICU 2.0 +*/ +U_STABLE void U_EXPORT2 +udat_parseCalendar(const UDateFormat* format, + UCalendar* calendar, + const UChar* text, + int32_t textLength, + int32_t *parsePos, + UErrorCode *status); + +/** +* Determine if an UDateFormat will perform lenient parsing. +* With lenient parsing, the parser may use heuristics to interpret inputs that do not +* precisely match the pattern. With strict parsing, inputs must match the pattern. +* @param fmt The formatter to query +* @return TRUE if fmt is set to perform lenient parsing, FALSE otherwise. +* @see udat_setLenient +* @stable ICU 2.0 +*/ +U_STABLE UBool U_EXPORT2 +udat_isLenient(const UDateFormat* fmt); + +/** +* Specify whether an UDateFormat will perform lenient parsing. +* With lenient parsing, the parser may use heuristics to interpret inputs that do not +* precisely match the pattern. With strict parsing, inputs must match the pattern. +* @param fmt The formatter to set +* @param isLenient TRUE if fmt should perform lenient parsing, FALSE otherwise. +* @see dat_isLenient +* @stable ICU 2.0 +*/ +U_STABLE void U_EXPORT2 +udat_setLenient( UDateFormat* fmt, + UBool isLenient); + +/** +* Get the UCalendar associated with an UDateFormat. +* A UDateFormat uses a UCalendar to convert a raw value to, for example, +* the day of the week. +* @param fmt The formatter to query. +* @return A pointer to the UCalendar used by fmt. +* @see udat_setCalendar +* @stable ICU 2.0 +*/ +U_STABLE const UCalendar* U_EXPORT2 +udat_getCalendar(const UDateFormat* fmt); + +/** +* Set the UCalendar associated with an UDateFormat. +* A UDateFormat uses a UCalendar to convert a raw value to, for example, +* the day of the week. +* @param fmt The formatter to set. +* @param calendarToSet A pointer to an UCalendar to be used by fmt. +* @see udat_setCalendar +* @stable ICU 2.0 +*/ +U_STABLE void U_EXPORT2 +udat_setCalendar( UDateFormat* fmt, + const UCalendar* calendarToSet); + +/** +* Get the UNumberFormat associated with an UDateFormat. +* A UDateFormat uses a UNumberFormat to format numbers within a date, +* for example the day number. +* @param fmt The formatter to query. +* @return A pointer to the UNumberFormat used by fmt to format numbers. +* @see udat_setNumberFormat +* @stable ICU 2.0 +*/ +U_STABLE const UNumberFormat* U_EXPORT2 +udat_getNumberFormat(const UDateFormat* fmt); + +/** +* Set the UNumberFormat associated with an UDateFormat. +* A UDateFormat uses a UNumberFormat to format numbers within a date, +* for example the day number. +* @param fmt The formatter to set. +* @param numberFormatToSet A pointer to the UNumberFormat to be used by fmt to format numbers. +* @see udat_getNumberFormat +* @stable ICU 2.0 +*/ +U_STABLE void U_EXPORT2 +udat_setNumberFormat( UDateFormat* fmt, + const UNumberFormat* numberFormatToSet); + +/** +* Get a locale for which date/time formatting patterns are available. +* A UDateFormat in a locale returned by this function will perform the correct +* formatting and parsing for the locale. +* @param localeIndex The index of the desired locale. +* @return A locale for which date/time formatting patterns are available, or 0 if none. +* @see udat_countAvailable +* @stable ICU 2.0 +*/ +U_STABLE const char* U_EXPORT2 +udat_getAvailable(int32_t localeIndex); + +/** +* Determine how many locales have date/time formatting patterns available. +* This function is most useful as determining the loop ending condition for +* calls to {@link #udat_getAvailable }. +* @return The number of locales for which date/time formatting patterns are available. +* @see udat_getAvailable +* @stable ICU 2.0 +*/ +U_STABLE int32_t U_EXPORT2 +udat_countAvailable(void); + +/** +* Get the year relative to which all 2-digit years are interpreted. +* For example, if the 2-digit start year is 2100, the year 99 will be +* interpreted as 2199. +* @param fmt The formatter to query. +* @param status A pointer to an UErrorCode to receive any errors +* @return The year relative to which all 2-digit years are interpreted. +* @see udat_Set2DigitYearStart +* @stable ICU 2.0 +*/ +U_STABLE UDate U_EXPORT2 +udat_get2DigitYearStart( const UDateFormat *fmt, + UErrorCode *status); + +/** +* Set the year relative to which all 2-digit years will be interpreted. +* For example, if the 2-digit start year is 2100, the year 99 will be +* interpreted as 2199. +* @param fmt The formatter to set. +* @param d The year relative to which all 2-digit years will be interpreted. +* @param status A pointer to an UErrorCode to receive any errors +* @see udat_Set2DigitYearStart +* @stable ICU 2.0 +*/ +U_STABLE void U_EXPORT2 +udat_set2DigitYearStart( UDateFormat *fmt, + UDate d, + UErrorCode *status); + +/** +* Extract the pattern from a UDateFormat. +* The pattern will follow the pattern syntax rules. +* @param fmt The formatter to query. +* @param localized TRUE if the pattern should be localized, FALSE otherwise. +* @param result A pointer to a buffer to receive the pattern. +* @param resultLength The maximum size of result. +* @param status A pointer to an UErrorCode to receive any errors +* @return The total buffer size needed; if greater than resultLength, the output was truncated. +* @see udat_applyPattern +* @stable ICU 2.0 +*/ +U_STABLE int32_t U_EXPORT2 +udat_toPattern( const UDateFormat *fmt, + UBool localized, + UChar *result, + int32_t resultLength, + UErrorCode *status); + +/** +* Set the pattern used by an UDateFormat. +* The pattern should follow the pattern syntax rules. +* @param format The formatter to set. +* @param localized TRUE if the pattern is localized, FALSE otherwise. +* @param pattern The new pattern +* @param patternLength The length of pattern, or -1 if null-terminated. +* @see udat_toPattern +* @stable ICU 2.0 +*/ +U_STABLE void U_EXPORT2 +udat_applyPattern( UDateFormat *format, + UBool localized, + const UChar *pattern, + int32_t patternLength); + +/** + * The possible types of date format symbols + * @stable ICU 2.6 + */ +typedef enum UDateFormatSymbolType { + /** The era names, for example AD */ + UDAT_ERAS, + /** The month names, for example February */ + UDAT_MONTHS, + /** The short month names, for example Feb. */ + UDAT_SHORT_MONTHS, + /** The weekday names, for example Monday */ + UDAT_WEEKDAYS, + /** The short weekday names, for example Mon. */ + UDAT_SHORT_WEEKDAYS, + /** The AM/PM names, for example AM */ + UDAT_AM_PMS, + /** The localized characters */ + UDAT_LOCALIZED_CHARS, + /** The long era names, for example Anno Domini */ + UDAT_ERA_NAMES, + /** The narrow month names, for example F */ + UDAT_NARROW_MONTHS, + /** The narrow weekday names, for example N */ + UDAT_NARROW_WEEKDAYS, + /** Standalone context versions of months */ + UDAT_STANDALONE_MONTHS, + UDAT_STANDALONE_SHORT_MONTHS, + UDAT_STANDALONE_NARROW_MONTHS, + /** Standalone context versions of weekdays */ + UDAT_STANDALONE_WEEKDAYS, + UDAT_STANDALONE_SHORT_WEEKDAYS, + UDAT_STANDALONE_NARROW_WEEKDAYS, + /** The quarters, for example 1st Quarter */ + UDAT_QUARTERS, + /** The short quarter names, for example Q1 */ + UDAT_SHORT_QUARTERS, + /** Standalone context versions of quarters */ + UDAT_STANDALONE_QUARTERS, + UDAT_STANDALONE_SHORT_QUARTERS + +} UDateFormatSymbolType; + +struct UDateFormatSymbols; +/** Date format symbols. + * For usage in C programs. + * @stable ICU 2.6 + */ +typedef struct UDateFormatSymbols UDateFormatSymbols; + +/** +* Get the symbols associated with an UDateFormat. +* The symbols are what a UDateFormat uses to represent locale-specific data, +* for example month or day names. +* @param fmt The formatter to query. +* @param type The type of symbols to get. One of UDAT_ERAS, UDAT_MONTHS, UDAT_SHORT_MONTHS, +* UDAT_WEEKDAYS, UDAT_SHORT_WEEKDAYS, UDAT_AM_PMS, or UDAT_LOCALIZED_CHARS +* @param symbolIndex The desired symbol of type type. +* @param result A pointer to a buffer to receive the pattern. +* @param resultLength The maximum size of result. +* @param status A pointer to an UErrorCode to receive any errors +* @return The total buffer size needed; if greater than resultLength, the output was truncated. +* @see udat_countSymbols +* @see udat_setSymbols +* @stable ICU 2.0 +*/ +U_STABLE int32_t U_EXPORT2 +udat_getSymbols(const UDateFormat *fmt, + UDateFormatSymbolType type, + int32_t symbolIndex, + UChar *result, + int32_t resultLength, + UErrorCode *status); + +/** +* Count the number of particular symbols for an UDateFormat. +* This function is most useful as for detemining the loop termination condition +* for calls to {@link #udat_getSymbols }. +* @param fmt The formatter to query. +* @param type The type of symbols to count. One of UDAT_ERAS, UDAT_MONTHS, UDAT_SHORT_MONTHS, +* UDAT_WEEKDAYS, UDAT_SHORT_WEEKDAYS, UDAT_AM_PMS, or UDAT_LOCALIZED_CHARS +* @return The number of symbols of type type. +* @see udat_getSymbols +* @see udat_setSymbols +* @stable ICU 2.0 +*/ +U_STABLE int32_t U_EXPORT2 +udat_countSymbols( const UDateFormat *fmt, + UDateFormatSymbolType type); + +/** +* Set the symbols associated with an UDateFormat. +* The symbols are what a UDateFormat uses to represent locale-specific data, +* for example month or day names. +* @param format The formatter to set +* @param type The type of symbols to set. One of UDAT_ERAS, UDAT_MONTHS, UDAT_SHORT_MONTHS, +* UDAT_WEEKDAYS, UDAT_SHORT_WEEKDAYS, UDAT_AM_PMS, or UDAT_LOCALIZED_CHARS +* @param symbolIndex The index of the symbol to set of type type. +* @param value The new value +* @param valueLength The length of value, or -1 if null-terminated +* @param status A pointer to an UErrorCode to receive any errors +* @see udat_getSymbols +* @see udat_countSymbols +* @stable ICU 2.0 +*/ +U_STABLE void U_EXPORT2 +udat_setSymbols( UDateFormat *format, + UDateFormatSymbolType type, + int32_t symbolIndex, + UChar *value, + int32_t valueLength, + UErrorCode *status); + +/** + * Get the locale for this date format object. + * You can choose between valid and actual locale. + * @param fmt The formatter to get the locale from + * @param type type of the locale we're looking for (valid or actual) + * @param status error code for the operation + * @return the locale name + * @stable ICU 2.8 + */ +U_STABLE const char* U_EXPORT2 +udat_getLocaleByType(const UDateFormat *fmt, + ULocDataLocaleType type, + UErrorCode* status); + +/** +* Extract the date pattern from a UDateFormat set for relative date formatting. +* The pattern will follow the pattern syntax rules. +* @param fmt The formatter to query. +* @param result A pointer to a buffer to receive the pattern. +* @param resultLength The maximum size of result. +* @param status A pointer to a UErrorCode to receive any errors +* @return The total buffer size needed; if greater than resultLength, the output was truncated. +* @see udat_applyPatternRelative +* @internal ICU 4.2 technology preview +*/ +U_INTERNAL int32_t U_EXPORT2 +udat_toPatternRelativeDate(const UDateFormat *fmt, + UChar *result, + int32_t resultLength, + UErrorCode *status); + +/** +* Extract the time pattern from a UDateFormat set for relative date formatting. +* The pattern will follow the pattern syntax rules. +* @param fmt The formatter to query. +* @param result A pointer to a buffer to receive the pattern. +* @param resultLength The maximum size of result. +* @param status A pointer to a UErrorCode to receive any errors +* @return The total buffer size needed; if greater than resultLength, the output was truncated. +* @see udat_applyPatternRelative +* @internal ICU 4.2 technology preview +*/ +U_INTERNAL int32_t U_EXPORT2 +udat_toPatternRelativeTime(const UDateFormat *fmt, + UChar *result, + int32_t resultLength, + UErrorCode *status); + +/** +* Set the date & time patterns used by a UDateFormat set for relative date formatting. +* The patterns should follow the pattern syntax rules. +* @param format The formatter to set. +* @param datePattern The new date pattern +* @param datePatternLength The length of datePattern, or -1 if null-terminated. +* @param timePattern The new time pattern +* @param timePatternLength The length of timePattern, or -1 if null-terminated. +* @param status A pointer to a UErrorCode to receive any errors +* @see udat_toPatternRelativeDate, udat_toPatternRelativeTime +* @internal ICU 4.2 technology preview +*/ +U_INTERNAL void U_EXPORT2 +udat_applyPatternRelative(UDateFormat *format, + const UChar *datePattern, + int32_t datePatternLength, + const UChar *timePattern, + int32_t timePatternLength, + UErrorCode *status); + + +#endif /* #if !UCONFIG_NO_FORMATTING */ + +#endif diff --git a/deps/prebuilt/include/icu/unicode/udatpg.h b/deps/prebuilt/include/icu/unicode/udatpg.h new file mode 100644 index 0000000000..3dc7e89f2d --- /dev/null +++ b/deps/prebuilt/include/icu/unicode/udatpg.h @@ -0,0 +1,586 @@ +/* +******************************************************************************* +* +* Copyright (C) 2007-2010, International Business Machines +* Corporation and others. All Rights Reserved. +* +******************************************************************************* +* file name: udatpg.h +* encoding: US-ASCII +* tab size: 8 (not used) +* indentation:4 +* +* created on: 2007jul30 +* created by: Markus W. Scherer +*/ + +#ifndef __UDATPG_H__ +#define __UDATPG_H__ + +#include "unicode/utypes.h" +#include "unicode/uenum.h" +#include "unicode/localpointer.h" + +/** + * \file + * \brief C API: Wrapper for DateTimePatternGenerator (unicode/dtptngen.h). + * + * UDateTimePatternGenerator provides flexible generation of date format patterns, + * like "yy-MM-dd". The user can build up the generator by adding successive + * patterns. Once that is done, a query can be made using a "skeleton", which is + * a pattern which just includes the desired fields and lengths. The generator + * will return the "best fit" pattern corresponding to that skeleton. + *

The main method people will use is udatpg_getBestPattern, since normally + * UDateTimePatternGenerator is pre-built with data from a particular locale. + * However, generators can be built directly from other data as well. + *

Issue: may be useful to also have a function that returns the list of + * fields in a pattern, in order, since we have that internally. + * That would be useful for getting the UI order of field elements. + */ + +/** + * Opaque type for a date/time pattern generator object. + * @stable ICU 3.8 + */ +typedef void *UDateTimePatternGenerator; + +/** + * Field number constants for udatpg_getAppendItemFormats() and similar functions. + * These constants are separate from UDateFormatField despite semantic overlap + * because some fields are merged for the date/time pattern generator. + * @stable ICU 3.8 + */ +typedef enum UDateTimePatternField { + /** @stable ICU 3.8 */ + UDATPG_ERA_FIELD, + /** @stable ICU 3.8 */ + UDATPG_YEAR_FIELD, + /** @stable ICU 3.8 */ + UDATPG_QUARTER_FIELD, + /** @stable ICU 3.8 */ + UDATPG_MONTH_FIELD, + /** @stable ICU 3.8 */ + UDATPG_WEEK_OF_YEAR_FIELD, + /** @stable ICU 3.8 */ + UDATPG_WEEK_OF_MONTH_FIELD, + /** @stable ICU 3.8 */ + UDATPG_WEEKDAY_FIELD, + /** @stable ICU 3.8 */ + UDATPG_DAY_OF_YEAR_FIELD, + /** @stable ICU 3.8 */ + UDATPG_DAY_OF_WEEK_IN_MONTH_FIELD, + /** @stable ICU 3.8 */ + UDATPG_DAY_FIELD, + /** @stable ICU 3.8 */ + UDATPG_DAYPERIOD_FIELD, + /** @stable ICU 3.8 */ + UDATPG_HOUR_FIELD, + /** @stable ICU 3.8 */ + UDATPG_MINUTE_FIELD, + /** @stable ICU 3.8 */ + UDATPG_SECOND_FIELD, + /** @stable ICU 3.8 */ + UDATPG_FRACTIONAL_SECOND_FIELD, + /** @stable ICU 3.8 */ + UDATPG_ZONE_FIELD, + /** @stable ICU 3.8 */ + UDATPG_FIELD_COUNT +} UDateTimePatternField; + +/** + * Masks to control forcing the length of specified fields in the returned + * pattern to match those in the skeleton (when this would not happen + * otherwise). These may be combined to force the length of multiple fields. + * Used with udatpg_getBestPatternWithOptions, udatpg_replaceFieldTypesWithOptions. + * @stable ICU 4.4 + */ +typedef enum UDateTimePatternMatchOptions { + /** @stable ICU 4.4 */ + UDATPG_MATCH_NO_OPTIONS = 0, + /** @stable ICU 4.4 */ + UDATPG_MATCH_HOUR_FIELD_LENGTH = 1 << UDATPG_HOUR_FIELD, + /** @internal ICU 4.4 */ + UDATPG_MATCH_MINUTE_FIELD_LENGTH = 1 << UDATPG_MINUTE_FIELD, + /** @internal ICU 4.4 */ + UDATPG_MATCH_SECOND_FIELD_LENGTH = 1 << UDATPG_SECOND_FIELD, + /** @stable ICU 4.4 */ + UDATPG_MATCH_ALL_FIELDS_LENGTH = (1 << UDATPG_FIELD_COUNT) - 1 +} UDateTimePatternMatchOptions; + +/** + * Status return values from udatpg_addPattern(). + * @stable ICU 3.8 + */ +typedef enum UDateTimePatternConflict { + /** @stable ICU 3.8 */ + UDATPG_NO_CONFLICT, + /** @stable ICU 3.8 */ + UDATPG_BASE_CONFLICT, + /** @stable ICU 3.8 */ + UDATPG_CONFLICT, + /** @stable ICU 3.8 */ + UDATPG_CONFLICT_COUNT +} UDateTimePatternConflict; + +/** + * Open a generator according to a given locale. + * @param locale + * @param pErrorCode a pointer to the UErrorCode which must not indicate a + * failure before the function call. + * @return a pointer to UDateTimePatternGenerator. + * @stable ICU 3.8 + */ +U_STABLE UDateTimePatternGenerator * U_EXPORT2 +udatpg_open(const char *locale, UErrorCode *pErrorCode); + +/** + * Open an empty generator, to be constructed with udatpg_addPattern(...) etc. + * @param pErrorCode a pointer to the UErrorCode which must not indicate a + * failure before the function call. + * @return a pointer to UDateTimePatternGenerator. + * @stable ICU 3.8 + */ +U_STABLE UDateTimePatternGenerator * U_EXPORT2 +udatpg_openEmpty(UErrorCode *pErrorCode); + +/** + * Close a generator. + * @param dtpg a pointer to UDateTimePatternGenerator. + * @stable ICU 3.8 + */ +U_STABLE void U_EXPORT2 +udatpg_close(UDateTimePatternGenerator *dtpg); + +#if U_SHOW_CPLUSPLUS_API + +U_NAMESPACE_BEGIN + +/** + * \class LocalUDateTimePatternGeneratorPointer + * "Smart pointer" class, closes a UDateTimePatternGenerator via udatpg_close(). + * For most methods see the LocalPointerBase base class. + * + * @see LocalPointerBase + * @see LocalPointer + * @stable ICU 4.4 + */ +U_DEFINE_LOCAL_OPEN_POINTER(LocalUDateTimePatternGeneratorPointer, UDateTimePatternGenerator, udatpg_close); + +U_NAMESPACE_END + +#endif + +/** + * Create a copy pf a generator. + * @param dtpg a pointer to UDateTimePatternGenerator to be copied. + * @param pErrorCode a pointer to the UErrorCode which must not indicate a + * failure before the function call. + * @return a pointer to a new UDateTimePatternGenerator. + * @stable ICU 3.8 + */ +U_STABLE UDateTimePatternGenerator * U_EXPORT2 +udatpg_clone(const UDateTimePatternGenerator *dtpg, UErrorCode *pErrorCode); + +/** + * Get the best pattern matching the input skeleton. It is guaranteed to + * have all of the fields in the skeleton. + * + * Note that this function uses a non-const UDateTimePatternGenerator: + * It uses a stateful pattern parser which is set up for each generator object, + * rather than creating one for each function call. + * Consecutive calls to this function do not affect each other, + * but this function cannot be used concurrently on a single generator object. + * + * @param dtpg a pointer to UDateTimePatternGenerator. + * @param skeleton + * The skeleton is a pattern containing only the variable fields. + * For example, "MMMdd" and "mmhh" are skeletons. + * @param length the length of skeleton + * @param bestPattern + * The best pattern found from the given skeleton. + * @param capacity the capacity of bestPattern. + * @param pErrorCode a pointer to the UErrorCode which must not indicate a + * failure before the function call. + * @return the length of bestPattern. + * @stable ICU 3.8 + */ +U_STABLE int32_t U_EXPORT2 +udatpg_getBestPattern(UDateTimePatternGenerator *dtpg, + const UChar *skeleton, int32_t length, + UChar *bestPattern, int32_t capacity, + UErrorCode *pErrorCode); + +/** + * Get the best pattern matching the input skeleton. It is guaranteed to + * have all of the fields in the skeleton. + * + * Note that this function uses a non-const UDateTimePatternGenerator: + * It uses a stateful pattern parser which is set up for each generator object, + * rather than creating one for each function call. + * Consecutive calls to this function do not affect each other, + * but this function cannot be used concurrently on a single generator object. + * + * @param dtpg a pointer to UDateTimePatternGenerator. + * @param skeleton + * The skeleton is a pattern containing only the variable fields. + * For example, "MMMdd" and "mmhh" are skeletons. + * @param length the length of skeleton + * @param options + * Options for forcing the length of specified fields in the + * returned pattern to match those in the skeleton (when this + * would not happen otherwise). For default behavior, use + * UDATPG_MATCH_NO_OPTIONS. + * @param bestPattern + * The best pattern found from the given skeleton. + * @param capacity + * the capacity of bestPattern. + * @param pErrorCode + * a pointer to the UErrorCode which must not indicate a + * failure before the function call. + * @return the length of bestPattern. + * @stable ICU 4.4 + */ +U_STABLE int32_t U_EXPORT2 +udatpg_getBestPatternWithOptions(UDateTimePatternGenerator *dtpg, + const UChar *skeleton, int32_t length, + UDateTimePatternMatchOptions options, + UChar *bestPattern, int32_t capacity, + UErrorCode *pErrorCode); + +/** + * Get a unique skeleton from a given pattern. For example, + * both "MMM-dd" and "dd/MMM" produce the skeleton "MMMdd". + * + * Note that this function uses a non-const UDateTimePatternGenerator: + * It uses a stateful pattern parser which is set up for each generator object, + * rather than creating one for each function call. + * Consecutive calls to this function do not affect each other, + * but this function cannot be used concurrently on a single generator object. + * + * @param dtpg a pointer to UDateTimePatternGenerator. + * @param pattern input pattern, such as "dd/MMM". + * @param length the length of pattern. + * @param skeleton such as "MMMdd" + * @param capacity the capacity of skeleton. + * @param pErrorCode a pointer to the UErrorCode which must not indicate a + * failure before the function call. + * @return the length of skeleton. + * @stable ICU 3.8 + */ +U_STABLE int32_t U_EXPORT2 +udatpg_getSkeleton(UDateTimePatternGenerator *dtpg, + const UChar *pattern, int32_t length, + UChar *skeleton, int32_t capacity, + UErrorCode *pErrorCode); + +/** + * Get a unique base skeleton from a given pattern. This is the same + * as the skeleton, except that differences in length are minimized so + * as to only preserve the difference between string and numeric form. So + * for example, both "MMM-dd" and "d/MMM" produce the skeleton "MMMd" + * (notice the single d). + * + * Note that this function uses a non-const UDateTimePatternGenerator: + * It uses a stateful pattern parser which is set up for each generator object, + * rather than creating one for each function call. + * Consecutive calls to this function do not affect each other, + * but this function cannot be used concurrently on a single generator object. + * + * @param dtpg a pointer to UDateTimePatternGenerator. + * @param pattern input pattern, such as "dd/MMM". + * @param length the length of pattern. + * @param baseSkeleton such as "Md" + * @param capacity the capacity of base skeleton. + * @param pErrorCode a pointer to the UErrorCode which must not indicate a + * failure before the function call. + * @return the length of baseSkeleton. + * @stable ICU 3.8 + */ +U_STABLE int32_t U_EXPORT2 +udatpg_getBaseSkeleton(UDateTimePatternGenerator *dtpg, + const UChar *pattern, int32_t length, + UChar *baseSkeleton, int32_t capacity, + UErrorCode *pErrorCode); + +/** + * Adds a pattern to the generator. If the pattern has the same skeleton as + * an existing pattern, and the override parameter is set, then the previous + * value is overriden. Otherwise, the previous value is retained. In either + * case, the conflicting status is set and previous vale is stored in + * conflicting pattern. + *

+ * Note that single-field patterns (like "MMM") are automatically added, and + * don't need to be added explicitly! + * + * @param dtpg a pointer to UDateTimePatternGenerator. + * @param pattern input pattern, such as "dd/MMM" + * @param patternLength the length of pattern. + * @param override When existing values are to be overridden use true, + * otherwise use false. + * @param conflictingPattern Previous pattern with the same skeleton. + * @param capacity the capacity of conflictingPattern. + * @param pLength a pointer to the length of conflictingPattern. + * @param pErrorCode a pointer to the UErrorCode which must not indicate a + * failure before the function call. + * @return conflicting status. The value could be UDATPG_NO_CONFLICT, + * UDATPG_BASE_CONFLICT or UDATPG_CONFLICT. + * @stable ICU 3.8 + */ +U_STABLE UDateTimePatternConflict U_EXPORT2 +udatpg_addPattern(UDateTimePatternGenerator *dtpg, + const UChar *pattern, int32_t patternLength, + UBool override, + UChar *conflictingPattern, int32_t capacity, int32_t *pLength, + UErrorCode *pErrorCode); + +/** + * An AppendItem format is a pattern used to append a field if there is no + * good match. For example, suppose that the input skeleton is "GyyyyMMMd", + * and there is no matching pattern internally, but there is a pattern + * matching "yyyyMMMd", say "d-MM-yyyy". Then that pattern is used, plus the + * G. The way these two are conjoined is by using the AppendItemFormat for G + * (era). So if that value is, say "{0}, {1}" then the final resulting + * pattern is "d-MM-yyyy, G". + *

+ * There are actually three available variables: {0} is the pattern so far, + * {1} is the element we are adding, and {2} is the name of the element. + *

+ * This reflects the way that the CLDR data is organized. + * + * @param dtpg a pointer to UDateTimePatternGenerator. + * @param field UDateTimePatternField, such as UDATPG_ERA_FIELD + * @param value pattern, such as "{0}, {1}" + * @param length the length of value. + * @stable ICU 3.8 + */ +U_STABLE void U_EXPORT2 +udatpg_setAppendItemFormat(UDateTimePatternGenerator *dtpg, + UDateTimePatternField field, + const UChar *value, int32_t length); + +/** + * Getter corresponding to setAppendItemFormat. Values below 0 or at or + * above UDATPG_FIELD_COUNT are illegal arguments. + * + * @param dtpg A pointer to UDateTimePatternGenerator. + * @param field UDateTimePatternField, such as UDATPG_ERA_FIELD + * @param pLength A pointer that will receive the length of appendItemFormat. + * @return appendItemFormat for field. + * @stable ICU 3.8 + */ +U_STABLE const UChar * U_EXPORT2 +udatpg_getAppendItemFormat(const UDateTimePatternGenerator *dtpg, + UDateTimePatternField field, + int32_t *pLength); + +/** + * Set the name of field, eg "era" in English for ERA. These are only + * used if the corresponding AppendItemFormat is used, and if it contains a + * {2} variable. + *

+ * This reflects the way that the CLDR data is organized. + * + * @param dtpg a pointer to UDateTimePatternGenerator. + * @param field UDateTimePatternField + * @param value name for the field. + * @param length the length of value. + * @stable ICU 3.8 + */ +U_STABLE void U_EXPORT2 +udatpg_setAppendItemName(UDateTimePatternGenerator *dtpg, + UDateTimePatternField field, + const UChar *value, int32_t length); + +/** + * Getter corresponding to setAppendItemNames. Values below 0 or at or above + * UDATPG_FIELD_COUNT are illegal arguments. + * + * @param dtpg a pointer to UDateTimePatternGenerator. + * @param field UDateTimePatternField, such as UDATPG_ERA_FIELD + * @param pLength A pointer that will receive the length of the name for field. + * @return name for field + * @stable ICU 3.8 + */ +U_STABLE const UChar * U_EXPORT2 +udatpg_getAppendItemName(const UDateTimePatternGenerator *dtpg, + UDateTimePatternField field, + int32_t *pLength); + +/** + * The date time format is a message format pattern used to compose date and + * time patterns. The default value is "{0} {1}", where {0} will be replaced + * by the date pattern and {1} will be replaced by the time pattern. + *

+ * This is used when the input skeleton contains both date and time fields, + * but there is not a close match among the added patterns. For example, + * suppose that this object was created by adding "dd-MMM" and "hh:mm", and + * its datetimeFormat is the default "{0} {1}". Then if the input skeleton + * is "MMMdhmm", there is not an exact match, so the input skeleton is + * broken up into two components "MMMd" and "hmm". There are close matches + * for those two skeletons, so the result is put together with this pattern, + * resulting in "d-MMM h:mm". + * + * @param dtpg a pointer to UDateTimePatternGenerator. + * @param dtFormat + * message format pattern, here {0} will be replaced by the date + * pattern and {1} will be replaced by the time pattern. + * @param length the length of dtFormat. + * @stable ICU 3.8 + */ +U_STABLE void U_EXPORT2 +udatpg_setDateTimeFormat(const UDateTimePatternGenerator *dtpg, + const UChar *dtFormat, int32_t length); + +/** + * Getter corresponding to setDateTimeFormat. + * @param dtpg a pointer to UDateTimePatternGenerator. + * @param pLength A pointer that will receive the length of the format + * @return dateTimeFormat. + * @stable ICU 3.8 + */ +U_STABLE const UChar * U_EXPORT2 +udatpg_getDateTimeFormat(const UDateTimePatternGenerator *dtpg, + int32_t *pLength); + +/** + * The decimal value is used in formatting fractions of seconds. If the + * skeleton contains fractional seconds, then this is used with the + * fractional seconds. For example, suppose that the input pattern is + * "hhmmssSSSS", and the best matching pattern internally is "H:mm:ss", and + * the decimal string is ",". Then the resulting pattern is modified to be + * "H:mm:ss,SSSS" + * + * @param dtpg a pointer to UDateTimePatternGenerator. + * @param decimal + * @param length the length of decimal. + * @stable ICU 3.8 + */ +U_STABLE void U_EXPORT2 +udatpg_setDecimal(UDateTimePatternGenerator *dtpg, + const UChar *decimal, int32_t length); + +/** + * Getter corresponding to setDecimal. + * + * @param dtpg a pointer to UDateTimePatternGenerator. + * @param pLength A pointer that will receive the length of the decimal string. + * @return corresponding to the decimal point. + * @stable ICU 3.8 + */ +U_STABLE const UChar * U_EXPORT2 +udatpg_getDecimal(const UDateTimePatternGenerator *dtpg, + int32_t *pLength); + +/** + * Adjusts the field types (width and subtype) of a pattern to match what is + * in a skeleton. That is, if you supply a pattern like "d-M H:m", and a + * skeleton of "MMMMddhhmm", then the input pattern is adjusted to be + * "dd-MMMM hh:mm". This is used internally to get the best match for the + * input skeleton, but can also be used externally. + * + * Note that this function uses a non-const UDateTimePatternGenerator: + * It uses a stateful pattern parser which is set up for each generator object, + * rather than creating one for each function call. + * Consecutive calls to this function do not affect each other, + * but this function cannot be used concurrently on a single generator object. + * + * @param dtpg a pointer to UDateTimePatternGenerator. + * @param pattern Input pattern + * @param patternLength the length of input pattern. + * @param skeleton + * @param skeletonLength the length of input skeleton. + * @param dest pattern adjusted to match the skeleton fields widths and subtypes. + * @param destCapacity the capacity of dest. + * @param pErrorCode a pointer to the UErrorCode which must not indicate a + * failure before the function call. + * @return the length of dest. + * @stable ICU 3.8 + */ +U_STABLE int32_t U_EXPORT2 +udatpg_replaceFieldTypes(UDateTimePatternGenerator *dtpg, + const UChar *pattern, int32_t patternLength, + const UChar *skeleton, int32_t skeletonLength, + UChar *dest, int32_t destCapacity, + UErrorCode *pErrorCode); + +/** + * Adjusts the field types (width and subtype) of a pattern to match what is + * in a skeleton. That is, if you supply a pattern like "d-M H:m", and a + * skeleton of "MMMMddhhmm", then the input pattern is adjusted to be + * "dd-MMMM hh:mm". This is used internally to get the best match for the + * input skeleton, but can also be used externally. + * + * Note that this function uses a non-const UDateTimePatternGenerator: + * It uses a stateful pattern parser which is set up for each generator object, + * rather than creating one for each function call. + * Consecutive calls to this function do not affect each other, + * but this function cannot be used concurrently on a single generator object. + * + * @param dtpg a pointer to UDateTimePatternGenerator. + * @param pattern Input pattern + * @param patternLength the length of input pattern. + * @param skeleton + * @param skeletonLength the length of input skeleton. + * @param options + * Options controlling whether the length of specified fields in the + * pattern are adjusted to match those in the skeleton (when this + * would not happen otherwise). For default behavior, use + * UDATPG_MATCH_NO_OPTIONS. + * @param dest pattern adjusted to match the skeleton fields widths and subtypes. + * @param destCapacity the capacity of dest. + * @param pErrorCode a pointer to the UErrorCode which must not indicate a + * failure before the function call. + * @return the length of dest. + * @stable ICU 4.4 + */ +U_STABLE int32_t U_EXPORT2 +udatpg_replaceFieldTypesWithOptions(UDateTimePatternGenerator *dtpg, + const UChar *pattern, int32_t patternLength, + const UChar *skeleton, int32_t skeletonLength, + UDateTimePatternMatchOptions options, + UChar *dest, int32_t destCapacity, + UErrorCode *pErrorCode); + +/** + * Return a UEnumeration list of all the skeletons in canonical form. + * Call udatpg_getPatternForSkeleton() to get the corresponding pattern. + * + * @param dtpg a pointer to UDateTimePatternGenerator. + * @param pErrorCode a pointer to the UErrorCode which must not indicate a + * failure before the function call + * @return a UEnumeration list of all the skeletons + * The caller must close the object. + * @stable ICU 3.8 + */ +U_STABLE UEnumeration * U_EXPORT2 +udatpg_openSkeletons(const UDateTimePatternGenerator *dtpg, UErrorCode *pErrorCode); + +/** + * Return a UEnumeration list of all the base skeletons in canonical form. + * + * @param dtpg a pointer to UDateTimePatternGenerator. + * @param pErrorCode a pointer to the UErrorCode which must not indicate a + * failure before the function call. + * @return a UEnumeration list of all the base skeletons + * The caller must close the object. + * @stable ICU 3.8 + */ +U_STABLE UEnumeration * U_EXPORT2 +udatpg_openBaseSkeletons(const UDateTimePatternGenerator *dtpg, UErrorCode *pErrorCode); + +/** + * Get the pattern corresponding to a given skeleton. + * + * @param dtpg a pointer to UDateTimePatternGenerator. + * @param skeleton + * @param skeletonLength pointer to the length of skeleton. + * @param pLength pointer to the length of return pattern. + * @return pattern corresponding to a given skeleton. + * @stable ICU 3.8 + */ +U_STABLE const UChar * U_EXPORT2 +udatpg_getPatternForSkeleton(const UDateTimePatternGenerator *dtpg, + const UChar *skeleton, int32_t skeletonLength, + int32_t *pLength); + +#endif diff --git a/include/Foundation/NSCalendar.h b/include/Foundation/NSCalendar.h index f6ed3fcd45..e2901b68e1 100644 --- a/include/Foundation/NSCalendar.h +++ b/include/Foundation/NSCalendar.h @@ -13,7 +13,7 @@ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLI #import #import #import -#import +#import @class NSDateComponents, NSTimeZone, NSLocale, NSDate; @@ -39,12 +39,6 @@ typedef uint32_t NSCalendarUnit; SB_EXPORT NSString * const NSGregorianCalendar; -#if defined( STARBOARD_PORT ) && defined( __cplusplus ) -namespace icu_48 { - class Calendar; -} -#endif - FOUNDATION_EXPORT_CLASS @interface NSCalendar : NSObject diff --git a/include/Foundation/NSDateFormatter.h b/include/Foundation/NSDateFormatter.h index 634cd77bff..a2eba15b49 100644 --- a/include/Foundation/NSDateFormatter.h +++ b/include/Foundation/NSDateFormatter.h @@ -30,7 +30,6 @@ typedef enum { FOUNDATION_EXPORT_CLASS @interface NSDateFormatter : NSFormatter -+ (void)setDefaultFormatterBehavior:(NSDateFormatterBehavior)behavior; + (NSString *)dateFormatFromTemplate:(NSString *)tmplate options:(NSUInteger)opts locale:(NSLocale *)locale; - initWithDateFormat:(NSString *)format allowNaturalLanguage:(BOOL)flag; // shouldn't this be "allows" ? @@ -39,35 +38,34 @@ FOUNDATION_EXPORT_CLASS // shouldn't this really exist anyway? - initWithDateFormat:(NSString *)format allowNaturalLanguage:(BOOL)flag locale:(NSDictionary *)locale; -- (NSString *)dateFormat; -- (BOOL)allowsNaturalLanguage; -- (NSDateFormatterBehavior)formatterBehavior; ++(void)setDefaultFormatterBehavior:(NSDateFormatterBehavior)behavior; +-(void)setFormatterBehavior:(NSDateFormatterBehavior)value; +-(NSDateFormatterBehavior)formatterBehavior; -- (NSDictionary *)locale; - -- (void)setDateFormat:(NSString *)format; - -- (NSString *)stringFromDate:(NSDate *)date; -- (NSArray *)shortStandaloneWeekdaySymbols; -- (NSArray *)standaloneWeekdaySymbols; +-(NSString *)stringFromDate:(NSDate *)date; +- (NSDate *)dateFromString:(NSString *)string; -- (void)setLenient:(BOOL)value; -- (void)setFormatterBehavior:(NSDateFormatterBehavior)value; +@property BOOL lenient; +@property BOOL allowsNaturalLanguage; -- (NSDate *)dateFromString:(NSString *)string; -- (NSDateFormatterStyle)dateStyle; -- (void)setDateStyle:(NSDateFormatterStyle)style; -- (void)setLocale:(NSLocale *)locale; +@property(copy) NSString *dateFormat; -- (NSCalendar *)calendar; -- (void)setCalendar:(NSCalendar *)calendar; -- (void)setTimeStyle:(NSDateFormatterStyle)style; +@property NSDateFormatterStyle timeStyle; +@property NSDateFormatterStyle dateStyle; -- (NSTimeZone *)timeZone; -- (void)setTimeZone:(NSTimeZone *)tz; +@property(copy) NSLocale *locale; +@property(copy) NSCalendar *calendar; +@property(copy) NSTimeZone *timeZone; +@property(copy) NSArray *monthSymbols; +@property(copy) NSArray *standaloneMonthSymbols; +@property(copy) NSArray *weekdaySymbols; +@property(copy) NSArray *shortWeekdaySymbols; +@property(copy) NSArray *shortStandaloneWeekdaySymbols; +@property(copy) NSArray *standaloneWeekdaySymbols; -- (NSArray *)monthSymbols; +@property(copy) NSString *AMSymbol; +@property(copy) NSString *PMSymbol; @end #endif /* _NSDATEFORMATTER_H_ */ diff --git a/include/Foundation/NSLocale.h b/include/Foundation/NSLocale.h index da8d77a4b3..b8aa408bdf 100644 --- a/include/Foundation/NSLocale.h +++ b/include/Foundation/NSLocale.h @@ -28,6 +28,7 @@ FOUNDATION_EXPORT NSString * const NSLocaleCollationIdentifier; FOUNDATION_EXPORT NSString * const NSCurrentLocaleDidChangeNotification; +FOUNDATION_EXPORT_CLASS @interface NSLocale : NSObject +systemLocale;