Convert string to date in my iPhone app

IosStringCocoa TouchDate Formatting

Ios Problem Overview


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").

I want to convert this to an NSDate.

What do I need to use to do that?

Ios Solutions


Solution 1 - Ios

Take a look at the class reference for NSDateFormatter. You use it like this:

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.

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.

Solution 2 - Ios

-(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];
}

Solution 3 - Ios

If you are storing dates in one of iOS' styles, it's far easier and less error prone to use this method:

// 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];

Solution 4 - Ios

NSString *dateString=@"2017-05-25";

NSDateFormatter *dateFormatter=[NSDateFormatter alloc]init];

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

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

date=[datFormatter dateFromString:dateString];

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionAppAspectView Question on Stackoverflow
Solution 1 - IosSam RitchieView Answer on Stackoverflow
Solution 2 - IosAnand PrakashView Answer on Stackoverflow
Solution 3 - IosPier-Luc GendreauView Answer on Stackoverflow
Solution 4 - IosShaik TamimView Answer on Stackoverflow