提问人:YosiFZ 提问时间:12/12/2011 最后编辑:jscsYosiFZ 更新时间:10/27/2017 访问量:3143
从 [NSDate date] 获取日期的时间缩短了几个小时
Getting date from [NSDate date] off by a few hours
答:
26赞
3 revsJosh Caswell
#1
NSDate
对象没有时区。它们代表了一个绝对的时刻。但是,当您要求一个人提供它(例如,通过打印它时),它必须选择一个时区。最合理的“默认”选择是格林威治标准时间。如果您自己不在格林威治标准时间,则日期似乎不正确,因为您自己的偏移量。description
NSLog()
应始终使用 an 创建用于显示的字符串。格式化程序的时区应设置为您的时区,这是默认设置。NSDateFormatter
2赞
Florian Burel
8/11/2016
#2
您可以像这样更正日期:
NSDate * dateGMT = [NSDate date];
NSTimeInterval secondsFromGMT = [[NSTimeZone localTimeZone] secondsFromGMT];
NSDate * correctDate = [dateGMT dateByAddingTimeInterval:secondsFromGMT];
0赞
Khurshid
3/15/2017
#3
-(NSDate *)getDateInCurrentSystemTimeZone
{
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];
return destinationDate;
}
上一个:如何查看iOS版本?
评论