Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I take a date and extract the day in iOS"

Tags:

date

ios

I have a webservice that returns the date in this format:

2013-04-14

How do i figure out what day this corresponds to?

like image 802
marciokoko Avatar asked Nov 30 '22 04:11

marciokoko


1 Answers

This code will take your string, convert it to an NSDate object and extract both the number of the day (14) and the name of the day (Sunday)

NSString *myDateString = @"2013-04-14";

// Convert the string to NSDate
NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
dateFormatter.dateFormat = @"yyyy-MM-dd";
NSDate *date = [dateFormatter dateFromString:myDateString];

// Extract the day number (14)
NSDateComponents *components = [[NSCalendar currentCalendar] components:NSDayCalendarUnit fromDate:date];
NSInteger day = [components day];

// Extract the day name (Sunday)
dateFormatter.dateFormat = @"EEEE";
NSString *dayName = [dateFormatter stringFromDate:date];

// Print
NSLog(@"Day: %d: Name: %@", day, dayName);

Note: This code is for ARC. If MRC, add [dateFormatter release] at the end.

like image 189
nebs Avatar answered Dec 04 '22 11:12

nebs