gpt4 book ai didi

objective-c - NSDateComponents关闭一个小时

转载 作者:行者123 更新时间:2023-12-01 17:59:49 25 4
gpt4 key购买 nike

尝试将这两个日期与NSDateComponents合并

“2012-09-03 00:00:00 +0000”&
“1970-01-01 08:00:00 +0000”


使用以下代码,我得到-> 2012-09-02 11:00:00 +0000

unsigned unitFlags = NSYearCalendarUnit | NSMonthCalendarUnit |  NSDayCalendarUnit;
NSDateComponents *comps = [[NSCalendar currentCalendar] components:unitFlags fromDate:session.date];
NSDate *day3 = [[NSCalendar currentCalendar] dateFromComponents:comps];

unitFlags = NSHourCalendarUnit | NSMinuteCalendarUnit | NSSecondCalendarUnit;
comps = [[NSCalendar currentCalendar] components:unitFlags fromDate:session.start];
comps.timeZone = [NSTimeZone timeZoneWithName:@"UTC"];
day3 = [[NSCalendar currentCalendar] dateByAddingComponents:comps toDate:day3 options:0];

最佳答案

找到了解决方案。

答案是:

unsigned unitFlags = NSYearCalendarUnit | NSMonthCalendarUnit |  NSDayCalendarUnit;
NSCalendar *cal = [[NSCalendar alloc] initWithCalendarIdentifier:NSGregorianCalendar];

cal.timeZone = [NSTimeZone timeZoneWithName:@"UTC"]; <--this is key

NSDateComponents *comps = [cal components:unitFlags fromDate:session.date];
comps.hour = 0;
comps.minute = 0;
NSDate *day3 = [cal dateFromComponents:comps];

unitFlags = NSHourCalendarUnit | NSMinuteCalendarUnit | NSSecondCalendarUnit;
NSDateComponents *hourComps = [cal components:unitFlags fromDate:session.start];

day3 = [cal dateByAddingComponents:hourComps toDate:day3 options:0];

给出上述日期的结果应为2012-09-02 08:00:00 +0000

关于objective-c - NSDateComponents关闭一个小时,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11892206/

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