简体   繁体   中英

How to get days in a week from today in objective c

I am trying to get the days of a week in reference to their date. Ex.: 14th October is a Wednesday. I am creating a collection view cell and displaying the date as follows. 在此处输入图片说明

In the 14th cell it would display Wednesday, but how to get the next day as Thursday, then Friday...and so on.

I have got todays date and which day it is as follows,

day = [components day];
week = [components month];
year = [components year];
weekday = [components weekday];
NSString *string = [NSString stringWithFormat:@"%ld.%ld.%ld", (long)day, (long)week, (long)year];
NSLog(@"%@",string);
NSDate *todayDate = [NSDate date]; // get today date
NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
[dateFormatter setDateFormat:@"EEEE"];
NSString *convertedDateString = [dateFormatter stringFromDate:todayDate];// here convert date in
NSLog(@"Today formatted date is %@",convertedDateString);

And i have found this method online, which returns the days in string when you pass the integer, but i am having trouble in this too, not understanding which integer to pass every time so I get different strings.

static inline NSString *stringFromWeekday(int weekday){
static NSString *strings[] = {
    @"Sunday",
    @"Monday",
    @"Tuesday",
    @"Wednesday",
    @"Thursday",
    @"Friday",
    @"Saturday",
};

return strings[weekday];

}

You already got everything in place. You should be getting the correct day name in the convertedDateString string. You just have to add 24 hours to your todayDate object and use the dateformatter again to get the next day.

NSDate *todayDate = [NSDate date]; // get today date
NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
[dateFormatter setDateFormat:@"EEEE"];
NSString *convertedDateString = [dateFormatter stringFromDate:todayDate];// here convert date in

You can get the next day like this.

NSDateComponents *dateComponents = [[NSCalendar currentCalendar] components:(NSDayCalendarUnit | NSMonthCalenderUnit | NSYearCalenderUnit | NSWeekdayCalendarUnit) fromDate:today];
[dateComponents setDay:dateComponents.day+1];
NSDate *nextDay = [dateComponents date];
// Get the day by following same approach in the top

You will get days in a week from today using below code.

NSDate *today = [NSDate date];
NSCalendar *gregorian = [[NSCalendar alloc]
                         initWithCalendarIdentifier:NSGregorianCalendar];
NSDateComponents *weekdayComponents =
                [gregorian components:(NSDayCalendarUnit | NSWeekdayCalendarUnit) fromDate:today];
NSInteger day = [weekdayComponents day];
NSInteger weekday = [weekdayComponents weekday];

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM