gpt4 book ai didi

ios - 获取前一个工作日

转载 作者:行者123 更新时间:2023-11-29 02:24:19 27 4
gpt4 key购买 nike

我需要从当前日期获取上一个工作日期。例如,如果当前日期是星期一,我需要获取星期五的日期。

我有以下代码可以从当前日期获取上一个日期。

-(NSDate*)previousDateFromDate:(NSDate*)date {

NSDate *now = date;
int daysToAdd = -1;

// set up date components
NSDateComponents *components = [[NSDateComponents alloc] init];
[components setDay:daysToAdd];

// create a calendar
NSCalendar *gregorian = [[NSCalendar alloc] initWithCalendarIdentifier:GregorianCalendar];
return [gregorian dateByAddingComponents:components toDate:now options:0];

我怎样才能实现这个目标?是通过计算当日指数的差异吗?

最佳答案

你的想法是对的,使用星期几是正确的方法,代码中的注释:

-(NSDate*)previousDateFromDate:(NSDate*)date
{
// Get the current calendar
NSCalendar *currentCal = [NSCalendar currentCalendar];

// Get current weekday, Sunday = 1
NSDateComponents *comps = [currentCal components:NSWeekdayCalendarUnit fromDate:date];
NSInteger weekday = comps.weekday;

// Determine the number of days to go back, assuming Sat -> Mond should go to Fri
NSInteger deltaDays = weekday == 1 ? -2 : (weekday == 2 ? -3 : -1);

// Create componets with the offset
NSDateComponents *offset = [NSDateComponents new];
offset.day = deltaDays;

// Calculate the required date
return [currentCal dateByAddingComponents:offset toDate:date options:0];
}

这假设当前日历是公历,您必须弄清楚它是否适用于其他日历。

HTH

关于ios - 获取前一个工作日,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27738859/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com