Resolved NSDate may not respond to +dateWithString

Discussion in 'iOS Programming' started by thedollarhunter, Nov 19, 2011.

  1. thedollarhunter, Nov 19, 2011
    Last edited: Nov 19, 2011

    macrumors member

    Joined:
    May 9, 2011
    Location:
    UK
    #1
    Having just discovered NSDate I am trying to return a time interval (a typedef of long as a positive or negative number of seconds if I understand it correctly)
    using the follow line of code

    Code:
    NSTimeInterval dateDiff = [[NSDate dateWithString:@"2011-11-17 00:00:00 +0000"] timeIntervalSinceNow];
    It seems to work but when I build I see a Warning message that says:
    NSDate may not respond to +dateWithString

    What am I doing wrong?

    Basically I want a check a given date to see if it is in the past or future.
     
  2. jiminaus, Nov 19, 2011
    Last edited: Nov 19, 2011

    macrumors 65816

    jiminaus

    Joined:
    Dec 16, 2010
    Location:
    Sydney
    #2
    There is no mention of dateWithString: in the iOS NSDate Class Reference. It is is the the Mac OS X NSDate Class Reference, but it's use is discouraged. If it does in fact work in iOS, it's private API, and should be avoided.

    You should send dateFromString: to an NSDateFormatter object instead, if your dates are in fact in a string.

    If you dates aren't in a string but instead you have them as separate components, check out the NSDateComponents class.
     
  3. thread starter macrumors member

    Joined:
    May 9, 2011
    Location:
    UK
    #3
    Thanks for pointing that out, I will use dateFromString instead.

    Another rookie question though, if I use NSDateFormatter to parse my string will it still work on devices with different regional settings?

    Code:
    NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
    [dateFormatter setDateFormat:@"dd MMM yyyy HH:mm:ss ZZ"];
    
    NSDate *dateToCheck = [dateFormatter dateFromString:@"24 Dec 2011 00:00:00 -0000"];
    
    NSTimeInterval dateDiff = [dateToCheck timeIntervalSinceNow];
     
  4. macrumors 65816

    jiminaus

    Joined:
    Dec 16, 2010
    Location:
    Sydney
    #4
    The user's locale and calendar are taken into consideration, so you want to set the locale before you set the format.

    See Parsing Date String. In particular take heed of the advice to use the en_US_POSIX locale, not the en_US locale.
     
  5. thread starter macrumors member

    Joined:
    May 9, 2011
    Location:
    UK
    #5
    Thanks for the pointer, that link is just what I was looking for.

    I've added the en_US_POSIX locale and tested it out by picking random International settings on the device (never knew iOS offered a Buddhist calendar) and it seems to work just fine.

    Again, thank you for taking the time to help others, it is really appreciated.
     

Share This Page