简体   繁体   中英

Converting NSStrings in an array into NSDates

I'm working on an assignment that allows the user to display events that are happening 'today'. I have parsed the XML file and stored the contents into an array. The contents of the XML file consists of a title, description, date etc. The dates are in NSString format and I want to convert them into NSDates and compare them with today's date before displaying them in a UITableView.

I'm new to obj-c and I've searched online for help on NSDate, but I couldn't find what I need. Any links, advice or help on this is really appreciated. Thanks in advance (:

suppose dateString contains the date in string format

first get date from string:-

 NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
   [formatter setDateFormat:@"dd/mm/yyyy"];
  NSDate *dateprevious = [formatter dateFromString:dateString];

Now get today date

    NSDate *date=[NSDate date]; 
[formatter setDateFormat:@"dd"];
    NSString *dateOfGame =[formatter stringFromDate:dateprevious];
    NSString *todaydate =[formatter stringFromDate:date];
[formatter release];

if([todaydate isEqualToString:dateknown])
{
NSLog(@"date matched");
}
NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
[dateFormatter setDateFormat:@"dd-MM-yyyy , hh:mm a"];
[dateFormatter setDateStyle:NSDateFormatterLongStyle];
NSDate *date = [[dateFormatter datefromString:date] retain];
[dateFormatter release];

You can use this one

Depending on the format of the string, you can use this :

+ (id)dateWithNaturalLanguageString:(NSString *)string

To compare two dates you will find here a lot of usefull answers:)

Have a look at NSDateFormatter

It has a method called dateFromString Like you could do the following:

NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
[formatter setDateFormat:@"dd/mm/yyyy"];
NSDate *date = [formatter dateFromString:@"5/5/2011"];

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM