Iphone NSDate从NSString调整到设备timzone
我有这样一个Iphone NSDate从NSString调整到设备timzone,iphone,ios,objective-c,nsdate,Iphone,Ios,Objective C,Nsdate,我有这样一个NSString: NSString *playTime = @"20:45";// GMT 我需要将此字符串转换为NSDate(仅小时和秒),然后调整为设备时区 例如: 如果用户设备时区设置为GMT,我需要这样的结果:@“20:45” 如果用户设备时区设置为GMT+2,我需要这样的结果:@“22:45” 根据您的要求,使用此代码进行日期转换 NSDateFormatter *dateFormat = [NSDateFormatter new]; [dateForma
NSString
:
NSString *playTime = @"20:45";// GMT
我需要将此字符串转换为NSDate
(仅小时和秒),然后调整为设备时区
例如:
如果用户设备时区设置为GMT,我需要这样的结果:@“20:45”
如果用户设备时区设置为GMT+2,我需要这样的结果:@“22:45” 根据您的要求,使用此代码进行日期转换
NSDateFormatter *dateFormat = [NSDateFormatter new];
[dateFormat setDateFormat:@"HH:mm"];
[dateFormat setTimeZone:[NSTimeZone localTimeZone]];
logDate = [dateFormat dateFromString:@"20:45"];
NSLog(@"Date %@",[dateFormat stringFromDate:logDate]);
试试这个
NSString *gmtDateString = @"20:45";
NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
[dateFormatter setTimeZone:[NSTimeZone timeZoneWithAbbreviation:@"UTC"]];
[dateFormatter setDateFormat:@"HH:mm"];
//Now you have date in GMT time zone by default dateFormatter timezone would be in local time zone
NSDate *date = [dateFormatter dateFromString:dateString];
//set to local time zone
[dateFormatter setTimeZone:[NSTimeZone localTimeZone]];
//Now you have string in localDate format
NSString *localDateString = [dateFormatter stringFromDate:date];
以下代码将计算w.r.t.本地时区的时间。
假设我的时区为
GMT+05:30
,则时间05:30
将变为00:00
NSString *playTime = @"20:45";
NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
formatter.dateFormat = @"HH:mm";
NSDate *date = [formatter dateFromString:playTime];
NSLog(@"%@",date);
日志是:
2000-01-01 15:15:00+0000
您可以在此处查看更多信息:为什么需要NSDate
来执行此操作?