如果陈述有脾气

发布于 2024-11-16 04:51:25 字数 877 浏览 2 评论 0原文

我不确定,但有时我的 if 语句会失败并在不应该的情况下显示错误的内容 有什么想法吗?

-(void)updateLabel{



   if (today > Date) {



    [only setHidden:YES];
    [untilRelease setHidden:YES];
    [theLabel setText:@"IS OUT"];


} else {


    NSCalendar *calendar = [[NSCalendar alloc] initWithCalendarIdentifier:NSGregorianCalendar];

    int units = NSMonthCalendarUnit | NSDayCalendarUnit | NSHourCalendarUnit | NSMinuteCalendarUnit | NSSecondCalendarUnit;

    NSDateComponents *components = [calendar components:units fromDate:[NSDate date] toDate:Date options:0];

    [theLabel setText:[NSString stringWithFormat:@"%d %@, %d %@ \n %d %@, %d %@ %d %@", [components month], @"Months", [components day], @"Days", [components hour], @"Hours", [components minute], @"Minutes and", [components second], @"Seconds"]];


}}

我将今天定义为 [NSDate date],Date 是纪元号。

任何帮助都会很棒

I'm not sure but sometimes my if statement fails and show the wrong thing when it shouldn't be
Any ideas?

-(void)updateLabel{



   if (today > Date) {



    [only setHidden:YES];
    [untilRelease setHidden:YES];
    [theLabel setText:@"IS OUT"];


} else {


    NSCalendar *calendar = [[NSCalendar alloc] initWithCalendarIdentifier:NSGregorianCalendar];

    int units = NSMonthCalendarUnit | NSDayCalendarUnit | NSHourCalendarUnit | NSMinuteCalendarUnit | NSSecondCalendarUnit;

    NSDateComponents *components = [calendar components:units fromDate:[NSDate date] toDate:Date options:0];

    [theLabel setText:[NSString stringWithFormat:@"%d %@, %d %@ \n %d %@, %d %@ %d %@", [components month], @"Months", [components day], @"Days", [components hour], @"Hours", [components minute], @"Minutes and", [components second], @"Seconds"]];


}}

I have defined today as [NSDate date] and Date is an epoch number.

Any help would be great

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

情释 2024-11-23 04:51:25

由于它们都是 NSDate 实例,因此执行此操作,

NSComparisonResult result = [today compare:Date];
if ( result == NSOrderedDescending ){ //  today > Date
    // After Date
} else {
    // Before Date
}

原始答案

如果 today[NSDate date]Date 是纪元数,您对它们的比较不正确。在比较它们之前,您也应该将今天转换为纪元号。

long currentTime = [today timeIntervalSince1970];
if ( currentTime > Date ) {
    // After `Date`
} else {
    // Before `Date`
}

Since they are both NSDate instances, do this,

NSComparisonResult result = [today compare:Date];
if ( result == NSOrderedDescending ){ //  today > Date
    // After Date
} else {
    // Before Date
}

Original Answer

If today is [NSDate date] and Date is an epoch number, you are comparing them incorrectly. You should convert today to epoch number too prior to comparing them.

long currentTime = [today timeIntervalSince1970];
if ( currentTime > Date ) {
    // After `Date`
} else {
    // Before `Date`
}
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文