格式化字符串中的日期
我正在尝试将日期从字符串格式化为另一种格式。
例如:将 2012-05-29 23:55:52
转换为 29/05 *newline* 2010
。
我认为我只是不明白 NSDate 和 NSDateFormatter 背后的逻辑..
任何帮助将不胜感激。谢谢 :)
I'm trying to format a date from a string into another format.
For example: 2012-05-29 23:55:52
into 29/05 *newline* 2010
.
I just don't get the logics behind NSDate and NSDateFormatter, I think..
Any help will be appreciated. Thanks :)
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(5)
您将需要创建一个 NSDateFormatter,然后将其 dateFormat 设置为匹配您拥有的第一个日期,例如:
这将设置您的日期格式化程序以识别您的日期字符串。然后,您可以使用此方法获取 NSDate 对象。
这将为您提供表示该日期的完整 NSDate 对象。现在您需要重新格式化日期并将其转回字符串,因此将格式化程序上的 dateFormat 设置为新格式,并获取返回日期的新字符串表示形式:
瞧!你有新的约会对象了:)
You will need to create an NSDateFormatter, and then set it's dateFormat to match the first date you have, eg:
That will set your date formatter to recognise your date string. You can then obtain an NSDate object from this using
This gives you a full NSDate object representing that date. Now you need to reformat the date and turn it back into a string, so set the dateFormat on your formatter to the new format, and get a new string representation of the returned date:
And voila! You have your new date :)
如果您只进行简单的字符串处理,则实际上不需要遍历日期对象。
If you're only doing simple string processing, Going through a date object is not really needed.
请查找以下代码将日期从一种格式转换为另一种格式。它将给出您当前区域的时间。
Please find following code to convert date from one format to another format. It will give time in your current zone.
对于那些喜欢使用扩展的人。
使用:
For those who prefer to use extension.
Use:
JFrank 的回答很好。但苹果表示:
“缓存格式化程序以提高效率”(https://developer.apple.com/library/archive/documentation/Cocoa/Conceptual/DataFormatting/Articles/dfDateFormatting10_4.html)以无效分配和丢弃。
因此,由于静态已经很懒惰了......
(为了清楚起见,我仅显示生成日期......输出格式类似......)
JFrank answer is good. But Apple says:
"Cache Formatters for Efficiency" (https://developer.apple.com/library/archive/documentation/Cocoa/Conceptual/DataFormatting/Articles/dfDateFormatting10_4.html) to void allocating and discarding.
So, as statics are already lazy...
(For clarity I show only generating a date.. output format is similar..)