4

I have an iOS app. One of the sections of the app shows a simple little weather forecast for a specific location. As part of this forecast, the app also shows some images. The images are either day based, in which case they will have a 'sun' image or night based, in which case they will have a 'moon icon'.

Anyway, I have come up with a 'botch-job' little method which can figure out if it is morning/afternoon or evening time. (It also factors in the season as well).

However I am not sure if it is any good and I am wandering if there is an official way of figuring this out? Maybe with some Apple API? What is a better way of approaching my problem? Here is my code:

Note: make sure you scroll through my code, there is quite a bit.

 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");
 }

Thanks for your time, Dan.

Supertecnoboff
  • 6,406
  • 11
  • 57
  • 98
  • 1
    Your logic only applies to a certain range of latitudes. There is no "standard API" to determine day and night. Why not base it off of actual sunrise and sunset times for the given location? – rmaddy May 22 '15 at 17:30
  • @rmaddy Presumably because he doesn't know how to _get_ the actual sunrise and sunset times for the given location... – matt May 22 '15 at 17:32
  • Saying it gets dark at 4pm in January will be confusing to users in the southern hemisphere. – rmaddy May 22 '15 at 17:33
  • There are open source libraries for this: http://stackoverflow.com/questions/4102873/objective-c-library-for-sunrise-and-sunset. – Josh Gafni May 22 '15 at 17:34
  • Offtopic - why is the moon used for night? The moon is out during the day just as much as it is out at night. – rmaddy May 22 '15 at 17:34
  • are you allowed to use weather API ? – Vizllx May 22 '15 at 17:35
  • @rmaddy Ah right... .thanks for that. In fact the very weather API I am using provides sunrise/sunset UNIX timestamps.... ah I could just them I suppose. – Supertecnoboff May 22 '15 at 17:36
  • @rmaddy Or should I just forget day/night and just show how hot/cold it is. If the weather API tells me its sunny right now, the I display sun icon. Full stop. Should I just no bother with a moon icon? – Supertecnoboff May 22 '15 at 17:37
  • @Supertecnoboff That makes the most sense. Compare against the sunrise and sunset. If between the two, it's daytime. – rmaddy May 22 '15 at 17:37
  • @rmaddy Wow!!! The logic for this is that simple?!!! If the current time is between sunset/sunrise, then its day, otherwise its night? Cool – Supertecnoboff May 22 '15 at 17:38
  • Actually, if it's between sunset and sunrise then it is night, not day. – rmaddy May 22 '15 at 17:41
  • 1
    @rmaddy urrmm are you sure? I went on OpenWeatherMap APi right now and noted down the sunrise and sunset times that it is giving for London, UK. It said 3:59 AM (sunrise) and 7:55 PM (sunset). Surely if the current time is ***between*** those two times, then it is day time? right?? – Supertecnoboff May 22 '15 at 17:46
  • @Supertecnoboff You keep saying different things. When it is between sunrise and sunset, then yes, it is day. When it is between sunset and sunrise it is night. Notice the difference? – rmaddy May 22 '15 at 18:11
  • @rmaddy Ah right sorry... the issue here was me misreading and misinterpreting what you said. Thanks anyway :) – Supertecnoboff May 22 '15 at 18:23

2 Answers2

3

Just in case you are allowed to use Weather API.

You can use the following library: OpenWeatherMapAPI

It gives the data in the following format:

NSDictionary that looks like this (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
}
Vizllx
  • 9,135
  • 1
  • 41
  • 79
  • Yes as it happens I am using OpenWeatherMap API to get the weather information. So I should just use the sunset/sunrise timestamps to detect if it is day or night right? – Supertecnoboff May 22 '15 at 17:40
  • What about comparing the current system time with the sunset time which you are getting from in the json, if the system time is greater than sunset time, then its night. @Supertecnoboff – Vizllx May 22 '15 at 17:45
  • Interesting idea, do you know how I can do this? Maybe some example of how I can do this in Objective-C. I know how to get the current time, but how do I compare it? – Supertecnoboff May 22 '15 at 17:49
  • @Supertecnoboff here is link how to compare http://stackoverflow.com/questions/5629154/compare-two-nsdates-for-same-date-time Let me know, if u need further clarification. – Vizllx May 22 '15 at 18:00
0
-(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];
}

}
Prankush
  • 41
  • 1
  • 5