iOS 5在DatePicker中选择日期

时间:2011-10-14 22:55:54

标签: nsdate nsdateformatter ios5 nsdatepicker

我希望在我的DatePicker选择日期,但我有一个滞后2小时的问题。

 // String From Date
NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
[dateFormatter setTimeStyle:NSDateFormatterFullStyle];
[dateFormatter setDateStyle:NSDateFormatterFullStyle];
[dateFormatter setLocale:[NSLocale currentLocale]];
[dateFormatter setDateFormat:@"yyyy-MM-dd HH:mm:ss ZZZ"];
NSDate *dateSelected = [datePicker date];
NSString *dateChoisie = [dateFormatter stringFromDate:dateSelected];
NSDate *dateFinal = [dateFormatter dateFromString:dateChoisie];

NSLog(@"dateSelected = %@", dateSelected);
NSLog(@"dateChoisie = %@", dateChoisie);
NSLog(@"dateFinal = %@", dateFinal);

结果:

2011-10-15 00:16:11.129 QuickEvent[25459:707] dateSelected = 2011-10-14 22:20:05 +0000
2011-10-15 00:16:11.132 QuickEvent[25459:707] dateChoisie = 2011-10-15 00:20:05 +0200
2011-10-15 00:16:11.138 QuickEvent[25459:707] dateFinal = 2011-10-14 22:20:05 +0000

1 个答案:

答案 0 :(得分:0)

尝试使用这种格式..

NSTimeZone *sourceTimeZone =[NSTimeZone systemTimeZone];
NSTimeZone *destinationTimeZone = [NSTimeZone timeZoneForSecondsFromGMT:(TIME_ZONE_THAT_YOU_WANTED*3600)];

NSInteger sourceSeconds =[sourceTimeZone secondsFromGMTForDate:date];
NSInteger destinationSeconds =[destinationTimeZone secondsFromGMTForDate:date];
NSTimeInterval interval = destinationSeconds - sourceSeconds;

NSDate *convertedDate =[[[NSDate alloc]initWithTimeInterval:interval sinceDate:date] autorelease];
return convertedDate;

例如,您可以为基于纽约时区的时间应用TIME_ZONE_THAT_YOU_WANTED = -8

谢谢, 阿伦。