在iPhone上使用NSDateFormatter,保护语言环境但丢失日期组件 [英] Using NSDateFormatter on the iPhone, protect locale but lose date components

查看:140
本文介绍了在iPhone上使用NSDateFormatter,保护语言环境但丢失日期组件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这是一个有点棘手的问题。我在iPhone上使用NSDateFormatter,但我只想显示没有年份组件的标准日期。但保留用户区域设置格式的日期。

This is a slightly tricky question. I am using NSDateFormatter on the iPhone but I wanted to only show a standard date without the years component. But retain the users locale formatting for their date.

我可以使用

[dateFormatter setDateFormat:@"h:mma EEEE MMMM d"];  // hurl.ws/43p9 (date formatting)

但是现在日期是我的in- nz格式例如7月7日星期三下午12:01所以我完全杀死了世界上任何其他用户的语言环境。

But now the date is in my in en-nz format eg 12:01PM Wednesday July 7. So I have totally killed the locale for any other users around the world.

我想说。


给我这个
用户区域的正确本地化日期,但省略年份
组件。

Give me the correct localized date for this users region but omit the years component.

由于日期显示为字符串,我很想将日期归结为日期,然后通过将其从字符串中删除来删除年份组件。

Since the date is being displayed as string, I am tempted to just fromat the date and then remove the year component by just cutting this out of the string.

推荐答案

您可以尝试以下方式:

//create a date formatter with standard locale, then:

// have to set a date style before dateFormat will give you a string back
[dateFormatter setDateStyle:NSDateFormatterMediumStyle];

// read out the format string
NSString *format = [dateFormatter dateFormat];
format = [format stringByReplacingOccurrencesOfString:@"y" withString:@""];
[dateFormatter setDateFormat:format];

有点黑客,但它应该有效。

Kind of a hack, but it should work.

编辑:您可能希望删除字符串的出现次数 @y, @y首先,如果你最后得到一些时髦的额外空格或逗号。

You may want to remove occurrences of the strings @"y," and @" y" first, in case you end up with some funky extra spaces or commas.

这篇关于在iPhone上使用NSDateFormatter,保护语言环境但丢失日期组件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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