gpt4 book ai didi

iphone - NSDate 没有返回我的本地时区/设备的默认时区

转载 作者:IT王子 更新时间:2023-10-29 07:44:51 25 4
gpt4 key购买 nike

我的本​​地和默认时区是 GMT +5,但是当我通过 NSDate 获取日期和时间时,它会返回 GMT 日期和时间。

例如,在设备上测试时我的代码和输出是 [device time zone Islamabad GMT +5]

 NSTimeZone *lo = [NSTimeZone localTimeZone];
NSLog(@" - current local timezone is %@",lo); // GMT +5

2010-12-28 20:56:11.785 Done[484:307] - current local timezone is Local Time Zone (Asia/Karachi (GMT+05:00) offset 18000)

NSTimeZone *df = [NSTimeZone defaultTimeZone];
NSLog(@" - current default timezone is %@",df); // GMT +5

2010-12-28 20:56:11.790 Done[484:307] - current default timezone is Asia/Karachi (GMT+05:00) offset 18000

但是

 NSDate *cDate = [NSDate date];
NSLog(@"current date by NSDate %@",cDate); //but NSDate show GMT
2010-12-28 20:56:11.794 Done[484:307] current date by NSDate 2010-12-28 15:56:11 GMT


NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
dateFormatter.dateFormat = @"yyyy-MM-dd'T'HH:mm";
//// NSTimeZone *gmt = [NSTimeZone ]
NSTimeZone *gmt = [NSTimeZone timeZoneWithAbbreviation:@"GMT+05:00"];
[dateFormatter setTimeZone:gmt];

NSString *timeStamp = [dateFormatter stringFromDate:[NSDate date]];
NSLog(@" date string object %@" ,timeStamp); // string From Date is GMT +5
2010-12-28 20:56:11.802 Done[484:307] date string object 2010-12-28T20:56


NSDate *datef = [dateFormatter dateFromString:timeStamp];
NSLog(@" date object %@" ,datef); // the date form above string gives again GMT
2010-12-28 20:56:11.809 Done[484:307] **date object 2010-12-28 15:56:00 GMT**

为什么 NSDate 不提供本地当前时间?请帮助...

最佳答案

试试这个...

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] autorelease];

这有助于响应当前系统时区。

关于iphone - NSDate 没有返回我的本地时区/设备的默认时区,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4547379/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com