ios 在我的 iPhone 应用程序中将字符串转换为日期
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/4380381/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Convert string to date in my iPhone app
提问by AppAspect
I have made a calendar application for the iPhone in which I have a date in string format (e.g. "Tue, 25 May 2010 12:53:58 +0000").
我为 iPhone 制作了一个日历应用程序,其中我有一个字符串格式的日期(例如“星期二,2010 年 5 月 25 日 12:53:58 +0000”)。
I want to convert this to an NSDate
.
我想将其转换为NSDate
.
What do I need to use to do that?
我需要用什么来做到这一点?
回答by Sam Ritchie
Take a look at the class reference for NSDateFormatter. You use it like this:
查看NSDateFormatter的类参考。你像这样使用它:
NSString *dateStr = @"Tue, 25 May 2010 12:53:58 +0000";
// Convert string to date object
NSDateFormatter *dateFormat = [[NSDateFormatter alloc] init];
[dateFormat setDateFormat:@"EE, d LLLL yyyy HH:mm:ss Z"];
NSDate *date = [dateFormat dateFromString:dateStr];
[dateFormat release];
For more information on how to customize that NSDateFormatter, try this reference guide.
有关如何自定义 NSDateFormatter 的更多信息,请尝试此参考指南。
EDIT:
编辑:
Just so you know, this is going to parse the full month name. If you want three letter month names, use LLL
instead of LLLL
.
请注意,这将解析完整的月份名称。如果您想要三个字母的月份名称,请使用LLL
代替LLLL
。
回答by Anand Prakash
-(NSString *)dateToFormatedDate:(NSString *)dateStr {
NSString *finalDate = @"2014-10-15";
NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
[dateFormatter setDateFormat:@"yyyy-MM-dd"];
NSDate *date = [dateFormatter dateFromString:dateStr];
[dateFormatter setDateFormat:@"EE, d MMM, YYYY"];
return [dateFormatter stringFromDate:date];
}
回答by Pier-Luc Gendreau
If you are storing dates in one of iOS' styles, it's far easier and less error prone to use this method:
如果您以 iOS 的一种样式存储日期,则使用此方法要容易得多且不易出错:
// Define a date formatter for storage, full style for more flexibility
NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
[dateFormatter setDateStyle:NSDateFormatterFullStyle];
[dateFormatter setTimeStyle:NSDateFormatterFullStyle];
// Use today as an example
NSDate *today = [NSDate date];
// Format to a string using predefined styles
NSString *dateString = [dateFormatter stringFromDate:today];
// Format back to a date using the same styles
NSDate *todayFromString = [dateFormatter dateFromString:dateString];
回答by Shaik Tamim
NSString *dateString=@"2017-05-25";
NSDateFormatter *dateFormatter=[NSDateFormatter alloc]init];
[dateFormatter setDateFormatter:@"MM-dd-yyyy"];
NSDate *date =[[NSDate alloc]init];
date=[datFormatter dateFromString:dateString];