设置NSDate的工作日不会更改日期?

时间:2015-04-13 16:59:20

标签: ios objective-c

我有一些日期,我希望将其工作日更改为另一天,同时用户执行某些操作。 当我将工作日更改为另一天/天时,结果NSDate会保留在该月的同一天,因此如果我将13.4.15设置为dayweek5将保持不变。

 NSCalendar *calendar = [NSCalendar currentCalendar];
    NSDateComponents *dateComponents = [calendar components:(NSCalendarUnitWeekday|NSCalendarUnitSecond|NSCalendarUnitMonth|NSCalendarUnitHour|NSCalendarUnitMinute|NSCalendarUnitYear|NSCalendarUnitDay) fromDate:lastdate];
    [dateComponents setWeekday:currentDay]; //set it to numbers from 0 to 7
    NSDate *date = [calendar dateFromComponents:dateComponents];
    lastdate=date;

    NSLog(@"%@",lastdate); //stay the same date of the month although i change the week day .

编辑: 从组件中删除日期单元不会解决问题,但会为新日期创建错误的月份日:

NSLog(@"%@",lastdate);//gives 14.4.15

//change last date day to the new day
NSCalendar *calendar = [NSCalendar currentCalendar];
NSDateComponents *dateComponents = [calendar components:(NSCalendarUnitWeekday|NSCalendarUnitSecond|NSCalendarUnitMonth|NSCalendarUnitHour|NSCalendarUnitMinute|NSCalendarUnitYear ) fromDate:lastdate];
[dateComponents setWeekday:currentDay];//added one day
NSDate *date = [calendar dateFromComponents:dateComponents];
lastdate=date;

NSLog(@"%@",lastdate); //gives 1.4.15

3 个答案:

答案 0 :(得分:1)

尝试将NSCalendarUnitWeekOfMonth标志添加到组件解析中。我假设日期组件不知道应该设置哪个星期,因此将忽略工作日。

NSDateComponents *dateComponents = [calendar components:(NSCalendarUnitSecond|NSCalendarUnitWeekOfMonth |NSCalendarUnitMonth|NSCalendarUnitHour|NSCalendarUnitMinute|NSCalendarUnitYear) fromDate:lastdate];

答案 1 :(得分:0)

我已经设法分3个步骤执行此操作,获取当前日期,获取其当天的日期,而不是计算添加天数,而不是将其添加到新日期:

//get new date with the new month day
NSDate *newdate=[[NSDate date] dateByAddingTimeInterval:60*60*24* (currentDay-today) ]; //current day is the day the user chosen . today, is day of today .

//extract the new month day
NSCalendar *calendar = [NSCalendar currentCalendar];
NSDateComponents *dateComponents = [calendar components:(NSCalendarUnitWeekday|NSCalendarUnitSecond|NSCalendarUnitMonth|NSCalendarUnitHour|NSCalendarUnitMinute|NSCalendarUnitYear|NSCalendarUnitDay ) fromDate:newdate];
long newDayOfMonth=[dateComponents day];


//create components from nob date
 NSDateComponents *nobComponents = [calendar components:(NSCalendarUnitWeekday|NSCalendarUnitSecond|NSCalendarUnitMonth|NSCalendarUnitHour|NSCalendarUnitMinute|NSCalendarUnitYear|NSCalendarUnitDay ) fromDate:lastdate];
[nobComponents setDay:newDayOfMonth];
 NSDate *date = [calendar dateFromComponents:dateComponents];
lastdate=date;




NSLog(@"final date:%@",lastdate);

答案 2 :(得分:0)

我不确定这是否适合您的使用案例,但此答案显示了如何使用给定的工作日创建新的NSDate实例:https://stackoverflow.com/a/31740820/849180