0

I'd like to compare and filter NSDates to determine whether there are any for today regarding the users current timezone.

Let's say I've a user located in Los Angeles (UTC-8 hours) and the following dates:

TargetDate
UTC:        2 pm (14:00) - 12. Feb 2017
LocalTime: 10 pm (22:00) - 12. Feb 2017

Now
UTC:       10 pm (22:00) - 11. Feb 2017   // Change of date!
LocalTime:  6 pm (06:00) - 12. Feb 2017

Today
UTC:       00 am (00:00) - 11. Feb 2017   // Begin of today

Tomorrow 
UTC:       00 am (00:00) - 12. Feb 2017

In the next step I'd like to compare the TargetDate, Today and Tomorrow to determine, if the TargetDate is between Today and Tomorrow. This is where the problem is. When I compare the dates I receive an answer that it is of course not between these dates.

+ (BOOL)date:(NSDate*)date isBetweenDate:(NSDate*)beginDate andDate:(NSDate*)endDate
{
    if ([date compare:beginDate] == NSOrderedAscending)
        return NO;

    if ([date compare:endDate] == NSOrderedDescending)
        return NO;

    return YES;
}

What I can do, is to convert the UTC date, TargetDate, to the local timezone but I'm very confused whether this is the best solution. In this post it's mentioned that you shouldn't do this because it confuses the whole problem.

Does anyone has an idea, how to solve this problem?

Community
  • 1
  • 1
user3191334
  • 1,148
  • 3
  • 15
  • 33

1 Answers1

0

The problem you are having is actually here:

Today
UTC:       00 am (00:00) - 11. Feb 2017   // Begin of today

Tomorrow 
UTC:       00 am (00:00) - 12. Feb 2017

You're deciding that the "day" is the UTC day. Instead, you need to determine the day in the target time zone.

Today
LocalTime: 00 am (00:00) - 11. Feb 2017   // Begin of today
UTC:       08 am (08:00) - 11. Feb 2017   // Equivalent UTC

Tomorrow 
LocalTime: 00 am (00:00) - 12. Feb 2017   // Begin of tomorrow
UTC:       08 am (08:00) - 12. Feb 2017   // Equivalent UTC

Do keep in mind a few other things:

  • Compare with half-open intervals: StartOfToday <= SomePointToday < StartOfTomorrow (inclusive start, exclusive end).
  • America/Los_Angeles is not always UTC-8. It switches to UTC-7 during daylight saving time.
  • Not every day starts at midnight. For example, America/Sao_Paulo on 2016-10-16 started at 01:00. The 00:00 hour was skipped for DST.
  • If you just care about some point on that day, rather than the entire day, compare at 12:00 noon, rather than at 00:00 midnight. It avoids the DST problem.
Matt Johnson-Pint
  • 230,703
  • 74
  • 448
  • 575
  • Thanks! So do you suggest to actually convert the date `Now` to the local timezone in order to determine the correct local date (`Today`and `Tomorrow`)? I'd like to summarise your answer into some example code. – user3191334 Feb 11 '17 at 19:10
  • Yes, exactly. I'd give you code, but while I do timezones in many languages, ObjectiveC isn't one of them. ;) – Matt Johnson-Pint Feb 11 '17 at 19:11