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

前端 未结 5 1558
佛祖请我去吃肉
佛祖请我去吃肉 2020-12-19 16:15

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

2013-04-14

How do i figure out what day this corresponds to?

5条回答
  •  再見小時候
    2020-12-19 17:12

    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.

提交回复
热议问题