在iOS中转换系统时区中的任何时区date
在iOS中将给定date转换为系统时区时,我面临问题。
来源date:2013-03-18 03:54:18 //其AM格式目标date应为:2013-03-18 03:30:15 //其PM格式。
我怎样才能得到这个?
我已经尝试了下面的代码,但得到错误的数据和差异。
NSDateFormatter *fmt = [[NSDateFormatter alloc] init]; fmt.dateFormat = @"yyyy-MM-dd HH:mm:ss"; NSLog(@"Post date::%@",postDate); NSDate *utc = [fmt dateFromString:postDate]; fmt.timeZone = [NSTimeZone systemTimeZone]; NSString *local = [fmt stringFromDate:utc]; NSLog(@" local %@", local); NSDate *date1 = [NSDate date]; NSString *currentDateString = [fmt stringFromDate:date1]; NSDate *currentDate = [fmt dateFromString:currentDateString]; NSUInteger flags = NSDayCalendarUnit | NSHourCalendarUnit | NSMinuteCalendarUnit; NSDateComponents *difference = [[NSCalendar currentCalendar] components:flags fromDate:utc toDate:currentDate options:0]; NSLog(@"difference::%d",[difference day]); NSLog(@"difference::%d",[difference hour]); NSLog(@"difference::%d",[difference minute]);
编辑:输出
Post date::2013-03-18 03:20:09 local 2013-03-18 03:20:09 difference::0 difference::13 difference::2
NSString *openingHour = @"15:05:35 "; NSDateFormatter *workingHoursFormatter = [[NSDateFormatter alloc] init]; NSTimeZone *timeZone = [NSTimeZone timeZoneWithName:@"UTC"]; [workingHoursFormatter setTimeZone:timeZone]; [workingHoursFormatter setDateFormat:@"HH:mm"]; NSDate *openingTime = [workingHoursFormatter dateFromString:openingHour];
你可以尝试上面的代码,它为我工作,改变date格式为您的需要
将你的代码从…
fmt.timeZone = [NSTimeZone systemTimeZone];
像这样
fmt.timeZone = [NSTimeZone localTimeZone];
这将适用于你…