【问题标题】:NSDateFormatter: week of year and first weekdayNSDateFormatter:一年中的一周和第一个工作日
【发布时间】:2012-02-20 11:36:04
【问题描述】:

我想从一个日期获取一个 NSString,日期格式如下:

MMEEEY ww

问题在于“ww”,即一年中的一周。我必须将这种格式与从后台获取的另一种格式进行比较。但是后台的第一个工作日是星期一,而 iOS 是星期日。所以,如果是星期天,字符串就不一样了,因为一年中的星期不一样。

问题是: 如何强制 NSDateFormatter 使用星期一作为第一个工作日?

我尝试使用 firstWeekday 属性设置为 2 的日历设置 NSDateFormatter 的日历属性,但它不起作用。

本文的要点:

NSCalendar * calendar = [[NSCalendar alloc] initWithCalendarIdentifier:NSGregorianCalendar];
calendar.firstWeekday = 2;
NSDateFormatter * dateFormatter = [[NSDateFormatter alloc] init];
dateFormatter.calendar = calendar;

编辑:诺亚回答后的测试

NSDateFormatter * dateFormatter = [[NSDateFormatter alloc] init];
NSLocale * locale = [[NSLocale alloc] initWithLocaleIdentifier:@"en"];
dateFormatter.locale = locale;
dateFormatter.dateFormat = @"MMEEEY ww";

NSDate * date = [NSDate dateWithTimeIntervalSince1970:1330251642]; // next sunday

NSLog(@"%@ -> %@", date, [dateFormatter stringFromDate:date]);

NSCalendar * calendar = [[NSCalendar alloc] initWithCalendarIdentifier:NSGregorianCalendar];
calendar.firstWeekday = 2;
dateFormatter.calendar = calendar;

NSLog(@"%@ -> %@", date, [dateFormatter stringFromDate:date]);

结果:

2012-02-24 11:31:27.878 Test[2546:15203] 2012-02-26 10:20:42 +0000 -> 02Sun2012 09
2012-02-24 11:31:27.880 Test[2546:15203] 2012-02-26 10:20:42 +0000 -> 02Sun2012 09

【问题讨论】:

    标签: iphone cocoa nsdateformatter nscalendar


    【解决方案1】:

    根据一些测试,日期格式化程序似乎支持日历设置。也许您可以举例说明您尝试格式化的日期、您想要的结果以及您得到的结果。

    NSDateFormatter * df = [[NSDateFormatter alloc] init];
    [df setDateFormat:@"MMEEEY ww"];
    
    NSDate *date;
    date = [NSDate dateWithString:@"2012-01-01 12:00:00 +0000"];
    NSLog(@"%@ -> %@", date, [df stringFromDate:date]);
    
    date = [NSDate dateWithString:@"2012-01-02 12:00:00 +0000"];
    NSLog(@"%@ -> %@", date, [df stringFromDate:date]);
    
    NSCalendar * calendar = [[NSCalendar alloc] initWithCalendarIdentifier:NSGregorianCalendar];
    calendar.firstWeekday = 2;
    df.calendar = calendar;
    
    date = [NSDate dateWithString:@"2012-01-01 12:00:00 +0000"];
    NSLog(@"%@ -> %@", date, [df stringFromDate:date]);
    
    date = [NSDate dateWithString:@"2012-01-02 12:00:00 +0000"];
    NSLog(@"%@ -> %@", date, [df stringFromDate:date]);
    

    结果:

    2012-02-22 12:42:17.020 test[68385:207] 2012-01-01 12:00:00 +0000 -> 01Sun2012 01
    2012-02-22 12:42:17.021 test[68385:207] 2012-01-02 12:00:00 +0000 -> 01Mon2012 01
    2012-02-22 12:42:17.022 test[68385:207] 2012-01-01 12:00:00 +0000 -> 01Sun2011 52
    2012-02-22 12:42:17.022 test[68385:207] 2012-01-02 12:00:00 +0000 -> 01Mon2012 01
    

    我不确定您是否想要 2011 年第 52 周的 2012 年 1 月 1 日部分,但这就是为什么我要问您想要什么结果。

    【讨论】:

    • 感谢您的回答。我试图做同样的事情,但对我来说,它仍然不起作用......不明白为什么......无论如何,我们决定不在日期格式中使用周数。奇怪的问题。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-08-19
    • 2015-04-04
    • 1970-01-01
    • 2019-01-08
    • 1970-01-01
    相关资源
    最近更新 更多