【问题标题】:how to get correct NSDate from NSString without using dateFormatter如何在不使用 dateFormatter 的情况下从 NSString 获取正确的 NSDate
【发布时间】:2015-05-06 10:20:29
【问题描述】:

因为 NSDateformatter 不能使用自定义日历,所以对于像这样的日历:

NSCalendar *ISO8601 = [[NSCalendar alloc] initWithCalendarIdentifier:NSCalendarIdentifierISO8601];
[ISO8601 setMinimumDaysInFirstWeek:7];
[ISO8601 setFirstWeekday:2];

如果我们需要一年中的一周,

此日历会将 2015-04-26 16:00:00 转换为 2015-16 周。

所以我会得到一个字符串2015-16th week

那么如何将字符串2015-16th week 转换为正确的NSDate 或DateComponents,这样如果转换这个新的NSDate 或dateComponents 就不会失去正确性?

【问题讨论】:

    标签: ios


    【解决方案1】:
    - (NSDate *) dateByAddingWeeks:(NSInteger)dWeeks {
    
    NSCalendar *gregorian = [[NSCalendar alloc] initWithCalendarIdentifier:NSCalendarIdentifierGregorian];
    NSDateComponents *components = [[NSDateComponents alloc] init];
    NSUInteger unitFlags = NSCalendarUnitYear | NSCalendarUnitMonth | NSCalendarUnitDay | NSCalendarUnitHour | NSCalendarUnitMinute | NSCalendarUnitTimeZone;
    components = [gregorian components:unitFlags fromDate:self];
    components.day = components.day + 7 * dWeeks;
    return [gregorian dateFromComponents:components];
    }
    

    不确定。您在寻找这种实用功能吗?

    【讨论】:

    • 不,作为你的答案,我想输入一个 NSString,并获得一个 NSDate,而不使用 NSDateFormatter。因为我设置了一个自定义日历:firstWeekDay=2MinimumDaysInFirstWeek=7
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-04-18
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多