从带语言环境的字符串到iphone sdk上的日期 [英] From string with locale to date on iphone sdk
本文介绍了从带语言环境的字符串到iphone sdk上的日期的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我试图找到一种将字符串转换为具有给定区域设置标识符的日期的方法. 例如,我有一个意大利日期(语言环境:it_IT),我想将其转换为有效的日期对象.
I trying to find a way to convert a string into a date with a given locale identifier. I have for example an italian date (locale: it_IT) I want to convert into a valid date object.
NSDate *GLDateWithString(NSString *string, NSString *localeIdentifier) {
[NSDateFormatter setDefaultFormatterBehavior:NSDateFormatterBehavior10_4];
NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
NSLocale *locale = [[NSLocale alloc] initWithLocaleIdentifier:localeIdentifier];
[formatter setLocale:locale];
[locale release];
NSDate *date = [formatter dateFromString:string];
[formatter release];
return date;
}
此代码无效,日期为nil. 我不知道该如何使用语言环境设置.
this code does not work, the date is nil. I can't figure out how I should use the locale setting for my purpose.
推荐答案
解决方案是使用NSDateFormatter的getObjectValue:forString:range:error:方法并按照以下步骤设置正确的日期和时间样式广告:
The solution is to use getObjectValue:forString:range:error: method of NSDateFormatter and set the correct date and time style ad follow:
- (NSDate *)dateWithString:(NSString *)string locale:(NSString *)localeIdentifier {
NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
[formatter setTimeStyle:NSDateFormatterNoStyle];
[formatter setDateStyle:NSDateFormatterShortStyle];
NSLocale *locale = [[NSLocale alloc] initWithLocaleIdentifier:localeIdentifier];
[formatter setLocale:locale];
[locale release];
NSDate *date = nil;
NSRange range = NSMakeRange(0, [string length]);
NSError *error = nil;
BOOL converted = NO;
converted = [formatter getObjectValue:&date forString:string range:&range error:&error];
[formatter release];
return converted? date : nil;
}
示例:
NSString *italianDate = @"30/10/2010";
NSString *italianLocale = @"it_IT";
NSDate *date = [myCustomFormatter dateWithString:italianDate locale:italianLocale];
这篇关于从带语言环境的字符串到iphone sdk上的日期的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文