Getting date from [NSDate date] off by a few hours

2018-12-31 01:07发布

I am using

NSDate *date = [NSDate date];

for getting the date, but the date I get is off by 2 hours.

3条回答
牵手、夕阳
2楼-- · 2018-12-31 01:44

You can get your date corrected like this:

NSDate * dateGMT = [NSDate date];
NSTimeInterval secondsFromGMT = [[NSTimeZone localTimeZone] secondsFromGMT];
NSDate * correctDate = [dateGMT dateByAddingTimeInterval:secondsFromGMT];
查看更多
与君花间醉酒
3楼-- · 2018-12-31 01:45
-(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;
}
查看更多
春风洒进眼中
4楼-- · 2018-12-31 01:54

NSDate objects don't have time zones. They represent an absolute moment in time. However, when you ask one for its description (by printing it with NSLog(), e.g.), it has to pick a time zone. The most reasonable "default" choice is GMT. If you're not in GMT yourself, the date will seem to be incorrect, by the amount of your own offset.

You should always use an NSDateFormatter to create a string for display. The formatter's timezone should be set to yours, which is the default.

查看更多
登录 后发表回答