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

前端 未结 5 1543
佛祖请我去吃肉
佛祖请我去吃肉 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:08

    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);
    
    0 讨论(0)
  • 2020-12-19 17:09

    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]);
    
    0 讨论(0)
  • 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.

    0 讨论(0)
  • 2020-12-19 17:15

    Swift 3:


    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.

    0 讨论(0)
  • 2020-12-19 17:18

    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];
    
    0 讨论(0)
提交回复
热议问题