gpt4 book ai didi

ios - NSString 到 NSDate 的转换 - 不正确的结果

转载 作者:行者123 更新时间:2023-11-29 03:26:05 27 4
gpt4 key购买 nike

简而言之,我计划获取当前日期时间,更改时间并通过将+0800应用于时区使其成为马来西亚本地时间。

结果出乎意料:

-(NSDate *)departureDateTime
{
NSDate *date = [NSDate date];
NSCalendar *gregorian = [[NSCalendar alloc] initWithCalendarIdentifier: NSGregorianCalendar];
NSDateComponents *components = [gregorian components: NSUIntegerMax fromDate: date];
[components setHour: 7];
[components setMinute: 59];
[components setSecond: 17];

NSDate *newDate = [gregorian dateFromComponents: components];

NSDateFormatter *dateFormat = [[NSDateFormatter alloc] init];
[dateFormat setDateFormat:@"yyyy-mm-dd HH:mm:ss Z"];
[dateFormat setLocale:[NSLocale currentLocale]];


NSString *newDateString = [NSString stringWithFormat:@"%@",newDate];
NSString *maskString = [NSString stringWithFormat:@"%@", [newDateString substringToIndex:20]];
NSString *append = [maskString stringByAppendingString:@"+0800"];
NSLog(@"%@",append);


NSDate *finalLocalDate = [dateFormat dateFromString:append];

return finalLocalDate;
}

结果:

对于 NSLog 附加:2013-12-07 23:59:17 +0800

但最终本地日期:2013-01-07 15:59:17 +0000

最佳答案

通过更短的解决方案找到了答案,所以我发布在这里以防将来对任何人有帮助。

对于返回,问题是不同的时区,所以通过添加这一行

[components setTimeZone:[NSTimeZone timeZoneForSecondsFromGMT:(+0*3600) ] ];

我们将时区设置为系统时区,然后删除不必要的代码:

-(NSDate *)departureDateTime
{
NSDate *date = [NSDate date];
NSCalendar *gregorian = [[NSCalendar alloc] initWithCalendarIdentifier: NSGregorianCalendar];
NSDateComponents *components = [gregorian components: NSUIntegerMax fromDate: date];

[components setTimeZone:[NSTimeZone timeZoneForSecondsFromGMT:(+0*3600) ] ];
[components setHour: 7];
[components setMinute: 59];
[components setSecond: 17];

NSDate *newDate = [gregorian dateFromComponents: components];
NSLog(@"%@",newDate);

return newDate;
}

正确结果:2013-12-08 07:59:17 +0000

关于ios - NSString 到 NSDate 的转换 - 不正确的结果,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20446495/

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