0

在 iOS 中将给定日期转换为系统时区时遇到问题。

源日期:2013-03-18 03:54:18 // 其为 AM 格式目标日期应为: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
4

2 回答 2

1

从...替换您的代码

fmt.timeZone = [NSTimeZone systemTimeZone];

像这样

fmt.timeZone = [NSTimeZone localTimeZone];

这对你有用...

于 2013-03-18T11:21:07.210 回答
0
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];

你能试试上面对我有用的代码吗,根据你的需要改变日期格式

于 2013-03-18T11:36:47.747 回答