ahm*_*mad 3 cocoa-touch nsdate nsdateformatter ios
我使用以下代码在用户时区中获取当前的NSDate
-(NSDate *)getCurrentDateinLocalTimeZone
{
NSDate* sourceDate = [NSDate date];
NSTimeZone* sourceTimeZone = [NSTimeZone timeZoneWithAbbreviation:@"GMT"];
NSTimeZone* destinationTimeZone = [NSTimeZone systemTimeZone];
NSInteger sourceGMTOffset = [sourceTimeZone secondsFromGMTForDate:sourceDate];
NSInteger destinationGMTOffset = [destinationTimeZone secondsFromGMTForDate:sourceDate];
NSTimeInterval interval = destinationGMTOffset - sourceGMTOffset;
NSDate* destinationDate = [[NSDate alloc] initWithTimeInterval:interval sinceDate:sourceDate] ;
NSDateFormatter *dateFormatter = [[NSDateFormatter alloc]init];
dateFormatter.dateFormat = @"yyyy-MM-dd HH:mm:ss";
return [dateFormatter dateFromString: [dateFormatter stringFromDate:destinationDate]];
}
Run Code Online (Sandbox Code Playgroud)
在我的应用程序中的其他一点,我想将日期格式化为"HH:mm"用于UI目的,所以我使用以下方法
-(NSString *)formatDate:(NSDate *)date
{
NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
[dateFormatter setTimeZone:[NSTimeZone systemTimeZone]];
dateFormatter.dateFormat = @"HH:mm";
return [dateFormatter stringFromDate:date];
}
Run Code Online (Sandbox Code Playgroud)
如果第二种方法的输出从第一种方法的结果移动了3个小时,,,我只想改变NSDate的格式而不是时间,我做错了什么?
该getCurrentDateinLocalTimeZone方法调整时区的日期,使用切断时区的格式字符串对其进行格式化,然后解析格式化的字符串.结果NSDate是UTC时区(+0000in 2012-07-15 16:28:23 +0000表示UTC时间).该formatDate:方法使用dateFormatter为本地时区设置的,产生不同的时间.您应该将格式化程序设置为使用UTC来获取正确的时间:replace
[dateFormatter setTimeZone:[NSTimeZone systemTimeZone]];
Run Code Online (Sandbox Code Playgroud)
同
[dateFormatter setTimeZone:[NSTimeZone timeZoneWithAbbreviation:@"GMT"]];
Run Code Online (Sandbox Code Playgroud)
在formatDate:方法中.
| 归档时间: |
|
| 查看次数: |
5208 次 |
| 最近记录: |