gpt4 book ai didi

ios - NSDate 下午 4 点以后

转载 作者:行者123 更新时间:2023-11-28 18:21:05 24 4
gpt4 key购买 nike

你好,我在这个网站上看到了很多 NSDate 比较但它们似乎都很复杂,因为我只需要知道如果现在的日期是下午 4 点之后或下午 4 点之前

也许有一些简单的方法可以实现这个目标?

[链接] ( Check if the time and date is between a particular date and time )

但它看起来又长又复杂,我只需要简单的 bool 答案是否超过下午 4 点

- (BOOL)checkTime
{

NSDate* now = [NSDate date];
NSDate *endDate;
[formatter setDateFormat:@"yyyy-MM-dd HH:mm:ss"];
endDate = [formatter dateFromString:@"2012-12-07 16:00:00"];//well here I have a problem how do I set end day to today 4pm ?

NSLog(@"%d",[now compare:endDate]);
if([now compare:endDate] < 0)
return YES;
else if([now compare:endDate] > 0)
return NO;
else
return NO;

}

编辑:在回答之后我想出了这段代码

- (BOOL)checkTime
{
NSDate *date = [NSDate date];
NSDateFormatter *df = [NSDateFormatter new];
[df setDateFormat:@"HH"];
int intS =9;
NSInteger HourStart = intS;
NSInteger hour = [[df stringFromDate:date] integerValue];
int hourE = 16;
NSInteger HourEnd = hourE;
if((hour >HourStart) && (hour < HourEnd))
return YES;
else
return NO;
}

目前它工作正常,但我不确定它是否适用于其他日历集等。

最佳答案

一般来说,我更喜欢使用 NSDateComponentsNSCalendar 进行这些类型的日历计算,因为您不知道用户使用的是什么日历。

下面是使用日期组件在 NSDate 的类别中进行比较的方法:

#import <Foundation/Foundation.h>

@interface NSDate (Foo)
- (BOOL)isAfterFourPM;
@end

@implementation NSDate (Foo)

- (BOOL)isAfterFourPM {
unsigned int flags = NSHourCalendarUnit;
NSDateComponents *comps = [[NSCalendar currentCalendar] components:flags fromDate:self];
return (comps.hour >= 16);
}

@end

int main(int argc, char *argv[]) {
@autoreleasepool {
NSDate *now = [NSDate date];
NSLog(@"is after 4 PM? - %@",([now isAfterFourPM]?@"YES":@"NO"));

// let's try with a different time (17h)
unsigned int flags = NSYearCalendarUnit | NSMonthCalendarUnit | NSDayCalendarUnit;
flags |= NSHourCalendarUnit;
NSDateComponents *currentComps = [[NSCalendar currentCalendar] components:flags fromDate:now];
currentComps.hour = 17;
NSDate *afterFourDate = [[NSCalendar currentCalendar] dateFromComponents:currentComps];

NSLog(@"is after 4 PM? - %@",([afterFourDate isAfterFourPM]?@"YES":@"NO"));
}
}

这打印:

2013-12-10 05:16:05.921 Untitled 2[43453:507] is after 4 PM? - NO
2013-12-10 05:16:05.921 Untitled 2[43453:507] is after 4 PM? - YES

(中部时间凌晨 5 点左右)

在这种情况下,您需要做的就是从使用当前日历的日期获取 NSHourCalendarUnit 组件,并比较 NSDateComponents< 上的 hour 属性 到 16。

关于ios - NSDate 下午 4 点以后,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20492435/

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