iphone shortdate有4位数的年份
-
21-08-2019 - |
题
我相信我只是失去了一些东西。但是,我用Google搜索这几天试图找到如何与NSDateFormatterShortStyle的风格显示一个NSDate时显示4位数的年份。请让我知道,如果你有一个解决方案。这是我现在使用的代码。
[NSDateFormatter setDefaultFormatterBehavior:NSDateFormatterBehavior10_4];
NSDateFormatter *dateFormatter = [[[NSDateFormatter alloc] init] autorelease ];
[dateFormatter setDateStyle:NSDateFormatterShortStyle];
[dateFormatter setTimeStyle:NSDateFormatterNoStyle];
// add label for birth
UILabel *birthday = [[UILabel alloc] initWithFrame:CGRectMake(125, 10, 100, 25)];
birthday.textAlignment = UITextAlignmentRight;
birthday.tag = kLabelTag;
birthday.font = [UIFont boldSystemFontOfSize:14];
birthday.textColor = [UIColor grayColor];
birthday.text = [dateFormatter stringFromDate:p.Birth];
解决方案
如果您需要四位数年,使用你想要的确切格式设置dateformat:
。缺点是你失去自动语言环境的格式化。
NSDateFormatter *dateFormatter = [[[NSDateFormatter alloc] init] autorelease];
[dateFormatter setDateFormat:@"MM/dd/yyyy"];
...
birthday.text = [dateFormatter stringFromDate:p.Birth];
如果您需要本地化,那么你可以尝试修改短风格的日期格式。
NSDateFormatter *dateFormatter = [[[NSDateFormatter alloc] init] autorelease ];
[dateFormatter setDateStyle:NSDateFormatterShortStyle];
[dateFormatter setTimeStyle:NSDateFormatterNoStyle];
if ([[dateFormatter dateFormat] rangeOfString:@"yyyy"].location == NSNotFound) {
NSString *fourDigitYearFormat = [[dateFormatter dateFormat] stringByReplacingOccurrencesOfString:@"yy" withString:@"yyyy"];
[dateFormatter setDateFormat:fourDigitYearFormat];
}
更新,对错误修正从最大Macleod的
其他提示
像我一样“因为我需要一个2位数的一年这样的事情在一个本地化的日期格式,这是一个非常古老的问题,在这里万一有人绊倒这里是我的解决方案:
NSLocale* curLocale = [NSLocale currentLocale];
NSString* dateFmt = [NSDateFormatter dateFormatFromTemplate: @"ddMMyyyy"
options: 0
locale: curLocale];
NSDateFormatter* formatter = [[[NSDateFormatter alloc] init] autorelease];
[formatter setDateFormat:dateFmt];
NSString* retText = [formatter stringFromDate:refDate];
return retText;
也许有人能抽空用它......
这是一个古老的线程,但因为我想做什么戴夫想,不能因为没有给出答案是正确的,这里是解决方案(万一有人曾经想同样的事情):
NSString *FormatString = [NSDateFormatter dateFormatFromTemplate:@"MM/dd/yyyy HH:mm" options:0 locale:[NSLocale currentLocale]];
NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
[formatter setDateFormat:FormatString];
//Parse date here with the formater (like [formatter stringFromDate:date])
[formatter release];
kCFDateFormatterShortStyle 指定短样式,通常只有数字,例如“37年11月23日”或“下午3:30”。
可用在Mac OS X V10.3和更高版本。
声明在CFDateFormatter.h。
NSDateFormatterShortStyle似乎并没有给你4位数字的年份。
不隶属于 StackOverflow