如何在用户的语言环境中获取一周中的某一天的名称?

我有一个介于1到7之间的数字,我想把它变成周一到周日用户的语言环境。 我可以这样做吗?如果是的话,怎么办?

一个NSDateFormatter可以给你的名字列表:

 NSDateFormatter * df = [[NSDateFormatter alloc] init]; [df setLocale: [NSLocale currentLocale]]; NSArray * weekdays = [df weekdaySymbols]; 

然后你可以索引像其他任何数组[weekdays objectAtIndex:dayIdx]; 但是,请注意, 第一个工作日可能因地区而异。 究竟是如何变化的(以及关于NSCalendar许多其他事情)在文档中没有特别好的解释。

当然可以。 下面是一个方法/函数,用于返回星期几的星期几名称,范围为0到6。

Objective C版本:

 - (NSString *)weekdayNameFromWeekdayNumber:(NSInteger)weekdayNumber { NSCalendar *calendar = [NSCalendar currentCalendar]; // Fetch the days of the week in words for the current language (Sunday to Saturday) NSArray *weekdaySymbols = calendar.weekdaySymbols; // Because the first week day changes depending on the region settings. // ie. In Bangladesh the first day of the week is Friday. In UK it is Monday NSInteger index = (weekdayNumber + calendar.firstWeekday - 1) % 7; return weekdaySymbols[index]; } 

和Swift 2版本:

 func weekdayNameFromWeekdayNumber(weekdayNumber: Int) -> String { let calendar = NSCalendar.currentCalendar() let weekdaySymbols = calendar.weekdaySymbols let index = (weekdayNumber + calendar.firstWeekday - 1) % 7 return weekdaySymbols[index] } 

和Swift 3.0版本:

 func weekdayNameFrom(weekdayNumber: Int) -> String { let calendar = Calendar.current let weekdaySymbols = calendar.weekdaySymbols let index = (weekdayNumber + calendar.firstWeekday - 1) % 7 return weekdaySymbols[index] } 
 NSArray *weekdaySymbols = [[NSDateFormatter alloc] weekdaySymbols]; 

您可以使用{weekdaySymbols,shortWeekdaySymbols,veryShortWeekdaySymbols}

基于gavdotnet优秀的解决scheme,欧洲版本(从星期一开始)是:

 func weekdayNameFromWeekdayNumber(weekdayNumber: Int) -> String { var EuroDay = weekdayNumber + 1 if EuroDay == 7 { EuroDay = 0 } let calendar = NSCalendar.currentCalendar() let weekdaySymbols = calendar.weekdaySymbols let index = EuroDay + calendar.firstWeekday - 1 return weekdaySymbols[index].uppercaseString } 

这是我的意见:

Swift 3,iOS8 +

 func weekdayNameFrom(weekdayNumber: Int) -> String { let calendar = Calendar.current let dayIndex = ((weekdayNumber - 1) + (calendar.firstWeekday - 1)) % 7 return calendar.weekdaySymbols[dayIndex] } 

请注意,您有3个可用的列表:

  • weekdaySymbols – > ["Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday"]
  • shortWeekdaySymbols – > ["Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat"]
  • veryShortWeekdaySymbols – > ["S", "M", "T", "W", "T", "F", "S"]