将 NSString 转换为日期
我有两个字符串: date1 = 3-3-2011;
我想转换为 2011 年 3 月 3 日并将其显示在标签中。
NSString *myString = 3-3-2011;
NSDateFormatter *dateFormatter = [[NSDateFormatter alloc]init];
[dateFormatter setDateFormat:@"d-MM-YYYY"];
NSDate *yourDate = [dateFormatter dateFromString:myString];
//now format this date to whatever you need…
[dateFormatter setDateFormat:@"d-MMM-YYYY"];
NSString *resultString = [dateFormatter stringFromDate:yourDate];
[dateFormatter release];
但 yourdate = 2010-12-25 18:30:00 +0000
resultstring = 26-Dec-2010
我想要 3-March-2010
请帮忙! 谢谢。
I have two strings: date1 = 3-3-2011;
and i want to convert in to 3-March-2011 and display it in label.
NSString *myString = 3-3-2011;
NSDateFormatter *dateFormatter = [[NSDateFormatter alloc]init];
[dateFormatter setDateFormat:@"d-MM-YYYY"];
NSDate *yourDate = [dateFormatter dateFromString:myString];
//now format this date to whatever you need…
[dateFormatter setDateFormat:@"d-MMM-YYYY"];
NSString *resultString = [dateFormatter stringFromDate:yourDate];
[dateFormatter release];
but yourdate = 2010-12-25 18:30:00 +0000
resultstring = 26-Dec-2010
i want 3-March-2010
please help!
Thank you.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
您可以使用
NSDateFormatter
。将当前字符串转换为
NSDate
对象,以便您可以将其转换为您想要的任何格式。
现在您可以将此
NSDate
转换为您想要的任何格式。Apple 关于
NSDateFormatter
的文档为You can use
NSDateFormatter
.Convert your current string to
NSDate
object, so that you canconvert it into any format you want.
Now you can convert this
NSDate
to any format you want.Apple's documentation on
NSDateFormatter
is here.看看 NSDateFormatter< /a>.特别是,请查看
dateFromString:
和stringFromDate:
方法。您需要将原始字符串转换为 NSDate,然后将该 NSDate 转换为另一个字符串。使用 NSDateFormatter 的一个技巧:确保始终设置区域设置。如果您不手动设置区域设置,则会出现有关 12/24 小时时钟设置的错误。我链接到的页面上的示例代码显示了如何设置区域设置。
Take a look at NSDateFormatter. In particular, take a look at the
dateFromString:
andstringFromDate:
methods. You'll need to convert your original string to an NSDate, then convert that NSDate to another string.One tip for using NSDateFormatter: be sure always to set a locale. If you don't manually set a locale, it has a bug regarding 12/24 hour clock settings. The example code on the page I linked to shows how to set a locale.
使用 dMY(或 MdY,具体取决于月份):
并参阅 Unicode 标准 在 Apple 文档中提到。
Use d-M-Y (or M-d-Y, depending on which is the month):
And see the Unicode standard referred to in the Apple docs.