How to take date and extract day in iOS "

I have a web service that returns a date in this format:

2013-04-14 

How do I determine which day this corresponds to?

+4
source share
5 answers

Alternative way to get a weekday:

 NSString *myDateString = @"2013-04-14"; NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init]; [dateFormatter setDateFormat:@"yyyy-MM-dd"]; NSDate *date = [dateFormatter dateFromString:myDateString]; NSDateComponents *components = [[NSCalendar currentCalendar] components:NSWeekdayCalendarUnit fromDate:date]; NSInteger weekday = [components weekday]; NSString *weekdayName = [dateFormatter weekdaySymbols][weekday - 1]; NSLog(@"%@ is a %@", myDateString, weekdayName); 
+6
source

This code will take your string, convert it to an NSDate object and retrieve both the day number (14) and the day name (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.

+11
source

You can use this code for me.

 NSString *dateString = @"2013-04-14"; NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init]; [dateFormatter setDateFormat:@"yyyy-MM-dd"]; NSDate *dateFromString = [[NSDate alloc] init]; dateFromString = [dateFormatter dateFromString:dateString]; [dateFormatter setDateFormat:@"EEEE"]; NSLog(@"%@", [dateFormatter stringFromDate:dateFromString]); 
+3
source

If you have 2013-04-14 stored in an NSString called date , you can do this ...

 NSArray *dateComponents = [date componentsSeperatedByString:@"-"]; NSString *day = [dateComponents lastObject]; 
0
source

Swift 3:


 let dateFromat = DateFormatter() datFormat.dateFormat = "EEEE" let name = datFormat.string(from: Date()) 

Bonus If you want to set your own date pattern instead of using Date() above:

 let datFormat = DateFormatter() datFormat.dateFormat = "yyyy-MM-dd'T'HH:mm:ssZZZZZ" let thisDate = datFormat.date(from: "2016-10-13T18:00:00-0400") 

Then call the 1st code after that.

0
source

All Articles