2014-10-07 33 views
0

如何从根据区域设置格式化的NSString获取NSDate(时间)?让我解释。基于设备的区域设置,我不得不myString的转换成NSDate的在HH:SS(意大利格式)如何从NSString timeStyle获取格式化为区域设置的NSDate

NSLocale *locale = [NSLocale autoupdatingCurrentLocale]; 
dateFormatter = [[NSDateFormatter alloc] init]; 
[dateFormatter setTimeStyle: NSDateFormatterShortStyle]; 
[dateFormatter setDateStyle: NSDateFormatterFullStyle]; 
[dateFormatter setLocale: [[NSLocale alloc] initWithLocaleIdentifier: [locale objectForKey: NSLocaleIdentifier]]]; 

我的NSString可以是:@“2014年1月1日6:15 PM”或@ “2014-01-01 18:15”或@“2014-01-01 6:15 MUU”或???? 我的结果必然是:@“2014年1月1日18:15”

[dateFormatter setDateFormat:@"????"]; 
NSDate *myDate = [dateFormatter dateFromString:myNSString]; 

我如何正确设置格式化的分区格式?

+0

请搜索。有无数个将日期/时间字符串从一种格式转换为另一种格式的例子。 – rmaddy 2014-10-07 16:49:14

+0

我尝试了两天,但找不到明确的解决方案。我做了很多次尝试,但都没有达到预期的效果 – Sgrappatore 2014-10-07 16:53:26

+0

您需要两个格式化程序。一个读取原始字符串来创建'NSDate',另一个读取'NSDate'到新的格式。 – rmaddy 2014-10-07 16:55:48

回答

2

你好,你必须编写类似的东西:

NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init]; 
dateFormatter.dateFormat = @"yyyy-MM-dd HH:mm"; 
[dateFormatter setTimeZone:[NSTimeZone timeZoneWithName:@"Europe/Italy"]];//include you're location from what country time you want 
NSString *dateString = [dateFormatter stringFromDate:[NSDate date]]; 
NSLog(@"New NSDate (NSDate): %@", [dateFormatter stringFromDate:date]); 
0
NSString* stringDate = @"January 1, 2000 at 9:10 PM";  
NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init]; 
[dateFormatter setDateStyle:NSDateFormatterLongStyle]; 
[dateFormatter setTimeStyle:NSDateFormatterShortStyle]; 

NSDate *tempDate  = [dateFormatter dateFromString:stringDate]; 
[dateFormatter setDateFormat:@"HH:mm"]; 

stringDate = [dateFormatter stringFromDate:tempDate];