iOS:如何从数字中获取正确的月份名称? [英] iOS: How to get a proper Month name from a number?

查看:88
本文介绍了iOS:如何从数字中获取正确的月份名称?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我知道NSDateformatter功能套件对人类来说是一个福音,但同时它对我来说非常困惑。我希望你能帮帮我。

I know that the NSDateformatter suite of functionality is a boon for mankind, but at the same time it is very confusing to me. I hope you can help me out.

在我的代码中,有一个代表一个月的int。所以:1将是1月,2月2日等。

Somewhere in my code, there is an int representing a month. So: 1 would be January, 2 February, etc.

在我的用户界面中,我想将此整数显示为正确的月份名称。此外,它应该遵守设备的区域设置。

In my user interface, I would like to display this integer as proper month name. Moreover, it should adhere to the locale of the device.

感谢您的见解

中庸时间,我做了以下几点:

In the mean time, I have done the following:

int monthNumber = 11
NSString * dateString = [NSString stringWithFormat: @"%d", monthNumber];

NSDateFormatter* dateFormatter = [[NSDateFormatter alloc] init];
[dateFormatter setDateFormat:@"MM"];
NSDate* myDate = [dateFormatter dateFromString:dateString];
[dateFormatter release];

NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
[formatter setDateFormat:@"MMMM"];
NSString *stringFromDate = [formatter stringFromDate:myDate];
[formatter release];

是这样做的吗?这似乎有点罗嗦。

is this the way to do it? It seems a bit wordy.

推荐答案

另一种选择是使用monthSymbols方法:

Another option is to use the monthSymbols method:

int monthNumber = 11;   //November
NSDateFormatter *df = [[[NSDateFormatter alloc] init] autorelease];
NSString *monthName = [[df monthSymbols] objectAtIndex:(monthNumber-1)];

请注意,您需要从1月12日的数字中减去1,因为月份符号为零 - 基于。

Note that you'll need to subtract 1 from your 1..12 monthNumber since monthSymbols is zero-based.

这篇关于iOS:如何从数字中获取正确的月份名称?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆