ios-在我的iPhone应用程序中将字符串转换为日期

我已经为iPhone制作了日历应用程序,其中有一个字符串格式的日期(例如“ Tue,25 May 2010 12:53:58 +0000”)。

我想将其转换为NSDate

我需要使用什么来做到这一点?

AppAspect asked 2019-11-17T15:42:43Z
4个解决方案
129 votes

看一下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];

有关如何自定义NSDateFormatter的更多信息,请尝试参考本指南。

编辑:

请注意,这将解析完整的月份名称。 如果要使用三个字母月份的名称,请使用LLL而不是LLLL

Sam Ritchie answered 2019-11-17T15:43:32Z
8 votes
-(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];
}
Anand Prakash answered 2019-11-17T15:43:51Z
5 votes

如果您以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];
Pier-Luc Gendreau answered 2019-11-17T15:44:19Z
-1 votes
NSString *dateString=@"2017-05-25";

NSDateFormatter *dateFormatter=[NSDateFormatter alloc]init];

[dateFormatter setDateFormatter:@"MM-dd-yyyy"];

NSDate *date =[[NSDate alloc]init];

date=[datFormatter dateFromString:dateString];
Shaik Tamim answered 2019-11-17T15:44:37Z
translate from https://stackoverflow.com:/questions/4380381/convert-string-to-date-in-my-iphone-app