从字符串格式化日期 [英] Format a date from a string
问题描述
我正在尝试将日期从字符串格式化为另一种格式.
I'm trying to format a date from a string into another format.
例如:将2012-05-29 23:55:52
转换为29/05 *newline* 2010
.
我认为我只是不了解NSDate和NSDateFormatter的逻辑.
I just don't get the logics behind NSDate and NSDateFormatter, I think..
任何帮助将不胜感激.谢谢:)
Any help will be appreciated. Thanks :)
推荐答案
您将需要创建NSDateFormatter,然后将其dateFormat设置为与您拥有的第一个日期匹配,例如:
You will need to create an NSDateFormatter, and then set it's dateFormat to match the first date you have, eg:
NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
[dateFormatter setDateFormat:@"yyyy-MM-dd HH:mm:ss"];
这将设置您的日期格式器以识别您的日期字符串.然后,您可以使用
That will set your date formatter to recognise your date string. You can then obtain an NSDate object from this using
NSDate *myDate = [dateFormatter dateFromString:myDateString]; // myDateString is the 2012-05-29 23:55:52 string
这为您提供了代表该日期的完整NSDate对象.现在,您需要重新格式化日期并将其重新转换为字符串,因此将格式化程序上的dateFormat设置为新格式,并获得返回日期的新字符串表示形式:
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:
[dateFormatter setDateFormat:@"dd/MM\nyyyy"];
NSString *newlyFormattedDateString = [dateFormatter stringFromDate:myDate];
[dateFormatter release], dateFormatter = nil;
瞧!您有新日期:)
这篇关于从字符串格式化日期的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!