Developer
Developer

Reputation: 6465

How can I convert string into date?

I have two strings: date1 = 3-5-2014; date2 = 4-2-2010;

I have to convert them in date and then compare them. I want the same format of date as in strings i.e., dd-mm-yyyy. How it can be done?

Upvotes: 4

Views: 3932

Answers (4)

Rakesh Bhatt
Rakesh Bhatt

Reputation: 4606

NSString *string=@"03-05-2014";
NSDateFormatter *dateFormatter = [[[NSDateFormatter alloc] init] autorelease];
[dateFormatter setDateFormat:@"dd-MM-yyyy"];
NSDate *dateFromString = [dateFormatter dateFromString:string];

enjoy...

Upvotes: 4

Inder Kumar Rathore
Inder Kumar Rathore

Reputation: 40018

    NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
    [dateFormatter setDateFormat:@"dd-MM-yyyy"];
    NSDate *date = [dateFormatter dateFromString:@"25-8-2010"];
    NSLog(@"%@", date);
    [dateFormatter release];

Hope this works for you
Cheers :)

Upvotes: 2

Jhaliya - Praveen Sharma
Jhaliya - Praveen Sharma

Reputation: 31730

Try with below

NSDateFormatter *dateFormat = [[NSDateFormatter alloc] init];
[dateFormat setDateFormat:@"MM/dd/yyyy h:mm a"];
NSDate *date = [dateFormat dateFromString:dateStr];
[dateFormat release];

here is the SO post

Convert NSString date to NSDate

Upvotes: 2

user94896
user94896

Reputation:

You can extract NSDate objects from strings using the NSDateFormatter class. See the Date Formatters section Apple's Data Formatting Guide for a detailed explanation and sample code.

Upvotes: 2

Related Questions