I have a webservice that returns the date in this format:
2013-04-14
How do i figure out what day this corresponds to?
An alternate method for getting the weekday can be:
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);
You can use this code it working 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]);
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.
let datFromat = DateFormatter()
datFormat.dateFormat = "EEEE"
let name = datFormat.string(from: Date())
Bonus: If you want to set your own date template 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 this.
If you have 2013-04-14
stored in a NSString
called date
, then you can do this...
NSArray *dateComponents = [date componentsSeperatedByString:@"-"];
NSString *day = [dateComponents lastObject];