【问题标题】:Detect when it is evening/night - NSDate - iOS检测何时是晚上/晚上 - NSDate - iOS
【发布时间】:2015-05-22 17:26:24
【问题描述】:

我有一个 iOS 应用程序。该应用程序的其中一个部分显示了特定位置的简单小天气预报。作为此预测的一部分,该应用程序还显示了一些图像。这些图像要么是基于白天的,在这种情况下它们将具有“太阳”图像,要么是基于夜晚的,在这种情况下它们将具有“月亮图标”。

不管怎样,我想出了一个“笨拙”的小方法,可以判断是早上/下午还是晚上。 (这也是季节的因素)。

但是我不确定这是否有好处,如果有官方方法可以解决这个问题,我正在徘徊?也许有一些Apple API?解决我的问题的更好方法是什么?这是我的代码:

注意:确保你滚动浏览我的代码,有很多。

 NSDateComponents *component = [[NSCalendar currentCalendar] components:(NSCalendarUnitMonth | NSCalendarUnitHour) fromDate:[NSDate date]];

 NSInteger hours = [component hour];
 NSInteger month = [component month];

 NSLog(@"\n\nHOUR IS: %ld", (long)hours);
 NSLog(@"MONTH IS: %ld", (long)month);

 NSInteger eveningHour = 0;

 switch (month) {

     case 12: case 1: case 2:
          // It is winter time... so days are very short.
          // December, January, February.
          eveningHour = 16;
       break;

     case 3: case 4: case 5:
          // Its spring time... days are getting a bit longer.
          // March, April, May.
          eveningHour = 17;
       break;

     case 6: case 7: case 8:
          // Its summer time... so days are longer.
          // June, July, August.
          eveningHour = 20;
       break;

     case 9: case 10: case 11:
          // Its fall (autumn)... days are getting shorter.
          // September, October, November.
          eveningHour = 17;
       break;

     default: break;
 }

 if ((hours >= 0) && (hours < 12)) {
      // Morning...
      // Display normal sun icon.
      NSLog(@"Morning");
 }

 else if ((hours >= 12) && (hours < eveningHour)) {
      // Afternoon...
      // Display normal sun icon.
      NSLog(@"Afternoon");
 }

 else if ((hours >= eveningHour) && (hours <= 24)) {
      // Evening/Night...
      // Display moon icon.
      NSLog(@"Evening");
 }

感谢您抽出宝贵时间,丹。

【问题讨论】:

  • 你的逻辑只适用于一定的纬度范围。没有“标准 API”来确定白天和黑夜。为什么不根据给定位置的实际日出和日落时间来计算呢?
  • @rmaddy 大概是因为他不知道如何获取给定位置的实际日出和日落时间...
  • 说一月份的下午 4 点天黑会让南半球的用户感到困惑。
  • @rmaddy urrmm 你确定吗?我现在继续使用 OpenWeatherMap APi,并记下了它为英国伦敦提供的日出和日落时间。上面写着 3:59 AM(日出)和 7:55 PM(日落)。当然,如果当前时间是这两个时间之间,那么它是白天时间吗?对吗??

标签: ios objective-c time nsdate nscalendar


【解决方案1】:

以防万一您被允许使用 Wea​​ther API。

您可以使用以下库:OpenWeatherMapAPI

它以下列格式给出数据:

NSDictionary 看起来像这样(json):

{
    coord: {
        lon: 10.38831,
        lat: 55.395939
    },
    sys: {
        country: "DK",
        sunrise: 1371695759, // this is an NSDate
        sunset: 1371758660   // this is also converted to a NSDate
    },
    weather: [
        {
            id: 800,
            main: "Clear",
            description: "Sky is Clear",
            icon: "01d"
        }
    ],
    base: "global stations",
    main: {
        temp: 295.006,      // this is the the temperature format you´ve selected
        temp_min: 295.006,  //                 --"--
        temp_max: 295.006,  //                 --"--
        pressure: 1020.58,
        sea_level: 1023.73,
        grnd_level: 1020.58,
        humidity: 80
    },
    wind: {
        speed: 6.47,
        deg: 40.0018
    },
    clouds: {
        all: 0
    },
    dt: 1371756382,
    id: 2615876,
    name: "Odense",
    cod: 200
}

【讨论】:

  • 是的,碰巧我正在使用 OpenWeatherMap API 来获取天气信息。所以我应该只使用日落/日出时间戳来检测是白天还是黑夜,对吗?
  • 如何将当前系统时间与您在 json 中获取的日落时间进行比较,如果系统时间大于日落时间,则为晚上。 @Supertecnoboff
  • 有趣的想法,你知道我该怎么做吗?也许是我如何在 Objective-C 中做到这一点的一些例子。我知道如何获取当前时间,但如何比较呢?
  • @Supertecnoboff 这里是链接如何比较stackoverflow.com/questions/5629154/… 如果您需要进一步说明,请告诉我。
【解决方案2】:
-(void)ShowTimeMessage
{
// For calculating the current date
NSDate *date = [NSDate date];

// Make Date Formatter
NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
[dateFormatter setDateFormat:@"hh a EEEE"];

// hh for hour mm for minutes and a will show you AM or PM
NSString *str = [dateFormatter stringFromDate:date];
// NSLog(@"%@", str);

// Sperate str by space i.e. you will get time and AM/PM at index 0 and 1 respectively
NSArray *array = [str componentsSeparatedByString:@" "];

// Now you can check it by 12. If < 12 means Its morning > 12 means its evening or night

NSString *message;
NSString *timeInHour;
NSString *am_pm;

NSString *DayOfWeek;
if (array.count>2)
{
    // am pm case
    timeInHour = array[0];
    am_pm = array[1];
    DayOfWeek  = array[2];
}
else if (array.count>1)
{
    // 24 hours case
    timeInHour = array[0];
    DayOfWeek = array[1];
}

if (am_pm)
{

    if ([timeInHour integerValue]>=4 && [timeInHour integerValue]<=9 && [am_pm isEqualToString:@"AM"])
    {
        message = [NSString stringWithFormat:@"Morning"];
    }
    else if (([timeInHour integerValue]>=10 && [timeInHour integerValue]!=12 && [am_pm isEqualToString:@"AM"]) || (([timeInHour integerValue]<4 || [timeInHour integerValue]==12) && [am_pm isEqualToString:@"PM"]))
    {
        message = [NSString stringWithFormat:@"Afternoon"];
    }
    else if ([timeInHour integerValue]>=4 && [timeInHour integerValue]<=9 && [am_pm isEqualToString:@"PM"])
    {
        message = [NSString stringWithFormat:@"Evening"];

    }
    else if (([timeInHour integerValue]>=10 && [timeInHour integerValue]!=12 && [am_pm isEqualToString:@"PM"]) || (([timeInHour integerValue]<4 || [timeInHour integerValue]==12) && [am_pm isEqualToString:@"AM"]))
    {
        message = [NSString stringWithFormat:@"Night"];
    }

}
else
{
    if ([timeInHour integerValue]>=4 && [timeInHour integerValue]<10)
    {
        message = [NSString stringWithFormat:@"Morning"];

    }
    else if ([timeInHour integerValue]>=10 && [timeInHour integerValue]<16)
    {
        message = [NSString stringWithFormat:@"Afternoon"];

    }
    else if ([timeInHour integerValue]>=16 && [timeInHour integerValue]<22)
    {
        message = [NSString stringWithFormat:@"Evening"];

    }
    else
    {
        message = [NSString stringWithFormat:@"Night"];

    }
}

if (DayOfWeek)
{
    _timeLbl.text=[NSString stringWithFormat:@"%@ %@",DayOfWeek,message];
}

}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2015-02-19
    • 2019-08-29
    • 1970-01-01
    • 1970-01-01
    • 2015-11-29
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多