gpt4 book ai didi

ios - NSDateComponents/NSDate : get the last sunday

转载 作者:塔克拉玛干 更新时间:2023-11-01 21:22:26 26 4
gpt4 key购买 nike

我知道有一些与此类似的问题,但我就是找不到我的代码有什么问题。

基本上我想要的是如果今天不是星期天,currentDate 设置为最后一个星期日。如果今天是星期日,我将 currentDate 设置为之前的星期日。

这是我正在尝试的方法。

  NSDateComponents *components = [[NSCalendar currentCalendar] components:  NSWeekCalendarUnit | NSYearCalendarUnit | NSWeekdayCalendarUnit fromDate:currentDate];

if (components.weekday == 1) { //Its sunday. We just need to subtract a week
[components setWeek: -1];
currentDate = [[NSCalendar currentCalendar] dateByAddingComponents:components toDate:currentDate options:0];

}else{ //If its not sunday we just go to sunday
[components setWeekday: 1];
currentDate = [[NSCalendar currentCalendar] dateFromComponents:components];

}

第一次执行这部分代码时,我得到了正确的答案。在我第一次得到奇怪的日期之后,比如 4026 年 12 月 2 日,并且年份一直在上升。

这是使它工作的代码:

   NSCalendar *calendar = [NSCalendar currentCalendar];
NSDateComponents *components = [calendar components: ( NSWeekCalendarUnit | NSWeekdayCalendarUnit | NSYearCalendarUnit) fromDate:currentDate];
int weekday = components.weekday;

if (weekday == 1) {
[components setWeek:components.week -1];
}else{
[components setWeekday:1];
}
currentDate = [calendar dateFromComponents:components];

最佳答案

如果您使用的是 iOS 8.0+,请将 nextDateAfterDate.SearchBackwards 选项一起使用

let calendar = NSCalendar.currentCalendar()
let options: NSCalendarOptions = [.MatchPreviousTimePreservingSmallerUnits, .SearchBackwards]
calendar.nextDateAfterDate(NSDate(), matchingUnit: .Weekday, value: 1, options: options)

关于ios - NSDateComponents/NSDate : get the last sunday,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20558022/

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