如果语句带有日期 [英] If statement with dates

查看:66
本文介绍了如果语句带有日期的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想要做的是使用大于小于符号的if语句。由于某种原因只有大于号的作品。这是我的代码:

what I am trying to do is make a if statement with dates using greater than less than signs. For some reason only the greater than sign works. Here is my code:

NSDate *currDate = [NSDate date];
NSDateFormatter *dateFormatter = [[NSDateFormatter alloc]init];
[dateFormatter setDateFormat:@"HHmm"];
NSString *dateString = [dateFormatter stringFromDate:currDate];
NSLog(@"%@",dateString);

if (dateString < @"0810" && dateString > @"0800") {
    NSLog(@"Homeroom");
}
else {
    NSLog(@"no");
}

这段代码的输出是如果时间是8:03: / p>

The output for this code would be if the time was 8:03:

2013-04-08 08:03:47.956 Schedule2.0[13200:c07] 0803
2013-04-08 08:03:47.957 Schedule2.0[13200:c07] no

所以在那里它只有更大的符号像这样:

If I were to make is so where it is only the greater then sign like this:

if (dateString > @"0800") {
    NSLog(@"Homeroom"); 
}
else {
    NSLog(@"no");
}

输出将是:

2013-04-08 08:03:29.748 Schedule2.0[14994:c07] 0803
2013-04-08 08:03:29.749 Schedule2.0[14994:c07] Homeroom


推荐答案

创建NSDate对象时间8:10和一个与8:00。现在你可以比较给定的日期与这两个日期

create a NSDate object with the time 8:10 and one with 8:00. Now you can compare the given date with both these dates

if(([date0800 compare:date] == NSOrderingAscending) && [date0810 compare:date] == NSOrderingDescending) )
{
    // date is between the other
}






创建边界日期您可以这样做


to create the boundaries dates you can do this

NSDate *date = [NSDate date]; // now
NSDateComponents *components = [[NSCalendar currentCalendar] components:( NSYearCalendarUnit | NSMonthCalendarUnit | NSDayCalendarUnit ) fromDate:date];
components.hour = 8;
components.minute = 0;

NSDate *date0800 = [[NSCalendar currentCalendar] dateFromComponents: components];
components.minute = 10;
NSDate *date0810 = [[NSCalendar currentCalendar] dateFromComponents: components];






< $ c>< 和> ,您可以使用日期对象的时间间隔。


if you insist of using operators like < and >, you can use the timeinterval of the date objects.

if(([date0800 timeIntervalSince1970] < [date timeIntervalSince1970]) && ([date0810 timeIntervalSince1970] > [date timeIntervalSince1970]))
{
    // date lays between the other two
}

code> == ,因为它可能是由于舍入错误错误。

but beware of checking == on it, as it could be faulty due to rounding errors.

这篇关于如果语句带有日期的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆