如何确定本地化月份的第一天?

How to determine the localized first day of month?

我必须找到每个月 1 日所在的 才能创建自定义日历;例如,2015 年 9 月 1 日是星期二,这使得星期二成为该月的第一天。

我有这段代码适用于英语国家,但对于其他国家,它失败了,因为它没有正确翻译。

    //  build date as start of month
monthDateComponents.year = components.year;
monthDateComponents.month = components.month;
monthDateComponents.day = 1;

NSCalendar *gregorian = [[NSCalendar alloc] initWithCalendarIdentifier:NSCalendarIdentifierGregorian];
NSDate *builtDate =[gregorian dateFromComponents: monthDateComponents];

NSDateFormatter *df = [NSDateFormatter new];
[df setDateFormat:@"E"];    
NSString *firstDay = [df stringFromDate:builtDate];

//  now, convert firstDay to the numeric day number
if([firstDay isEqual:NSLocalizedString(@"Sun",nil)])
    return 7;
else if([firstDay isEqual:NSLocalizedString(@"Mon",nil)])
    return 1;
else if([firstDay isEqual:NSLocalizedString(@"Tue",nil)])
    return 2;
else if([firstDay isEqual:NSLocalizedString(@"Wed",nil)])
    return 3;
else if([firstDay isEqual:NSLocalizedString(@"Thu",nil)])
    return 4;
else if([firstDay isEqual:NSLocalizedString(@"Fri",nil)])
    return 5;
else if([firstDay isEqual:NSLocalizedString(@"Sat",nil)])
    return 6;

有没有更好的方法,这样我就不必遍历每个国家/地区并找出每天的 3 个字符缩写是什么? (例如,在法语中,星期六的缩写 returns "sam."。)我现在的编码方式是,我需要知道我的应用程序本地化的每一种语言(其中 10 种) 使其正常工作。

提前致谢。

试试这个,它使用了 NSCalendar 的智能日历计算。

  NSDateComponents *components = [NSDateComponents new];
  components.day = 1;
  NSCalendar *gregorian = [[NSCalendar alloc] initWithCalendarIdentifier:NSCalendarIdentifierGregorian];

  NSDate *firstDayOfMonth = [gregorian nextDateAfterDate:builtDate matchingComponents:components options: NSCalendarMatchNextTime | NSCalendarSearchBackwards];
  NSInteger weekdayIndex = [gregorian component:NSCalendarUnitWeekday fromDate:firstDayOfMonth];
  NSLog(@"weekday number: %ld", weekdayIndex);
  return weekdayIndex;

你想要这个:

return [gregorian component:NSCalendarUnitWeekday fromDate:builtDate];

这会为您提供一个整数,告诉您该日期是星期几。 1 是星期天。