【问题标题】:parsing the date and getting the day off by 1, nsdate解析日期并将休息日减 1, nsdate
【发布时间】:2015-06-17 23:39:13
【问题描述】:

有两个像下面这样的结束日

A = 2029-12-31T00:00:00+00:00
B = 2029-12-31T12:00:00+00:00

我通过关注得到月、日和年

NSDateFormatter *endDateFormatter = [[NSDateFormatter alloc] init];
[endDateFormatter setDateFormat:@"yyyy-MM-dd'T'HH:mm:ssZ"];
NSDate *endDate = [endDateFormatter dateFromString:self[@"license"][@"endDate"]];
NSDateComponents *endDatecomponents = [[NSCalendar currentCalendar] components:NSDayCalendarUnit | NSMonthCalendarUnit | NSYearCalendarUnit fromDate:endDate];

这就是我为A得到的

Printing description of endDate:
2029-12-31 00:00:00 +0000
Printing description of endDatecomponents:
<NSDateComponents: 0x79e069e0>
    Calendar Year: 2029
    Month: 12
    Leap month: no
    Day: 30

对于B,我得到了

2029-12-31 12:00:00 +0000
Printing description of endDatecomponents:
<NSDateComponents: 0x7be8eb60>
    Calendar Year: 2029
    Month: 12
    Leap month: no
    Day: 31

我很困惑为什么 2029-12-31T00:00:00+00:00 只给我 1 天的假期。 有什么想法吗?

【问题讨论】:

    标签: ios objective-c nsdate nsdateformatter nsdatecomponents


    【解决方案1】:

    这是由于您的时区和 UTC 之间的差异。 2029-12-31T00:00:00+00:00 的值是 UTC 时区的 12 月 31 日。但是,当您设置日期组件时,您将返回您所在时区的日期,即当地时间 12 月 30 日。

    【讨论】:

    • 我试图阻止 UTC 转换为本地时区,但它确实有帮助。从 UTC 获得 12 月 31 日的任何想法。 ?
    • 我找到了方法。原来我必须用NSCalendar *utcCalendar = [[NSCalendar alloc] initWithCalendarIdentifier:NSGregorianCalendar]; [utcCalendar setTimeZone:[NSTimeZone timeZoneWithAbbreviation:@"UTC"]];
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-06-18
    相关资源
    最近更新 更多