Working with dates

Discussion in 'iOS Programming' started by idelovski, Jun 8, 2011.

  1. idelovski macrumors regular

    Sep 11, 2008
    What is the best way to store dates that represent just date, not the time.

    void  TestDate (void)
       NSDateComponents  *comps = [[NSDateComponents alloc] init];
       [comps setDay:31];
       [comps setMonth:12];
       [comps setYear:2009];
       NSCalendar  *cal = [[NSCalendar alloc] initWithCalendarIdentifier:NSGregorianCalendar];
       NSDate  *dt = [cal dateFromComponents:comps];
       [comps release];
       [cal release];
       NSDateFormatter  *dfmt = [[NSDateFormatter alloc] init];
       [dfmt setDateStyle:kCFDateFormatterShortStyle];
       NSString  *dateString = [dfmt stringFromDate:dt];
       [dfmt release];
       NSLog (@"Raw: %@,   Str: %@", dt, dateString);
    This code gives me this in console - I'm in Central European time zone:

    "Raw: 2009-12-30 23:00:00 +0000, Str: 31.12.2009."

    Somehow I think this may turn out as a problem. If my app puts this date into a file, then reads it in another time zone it may turn as Dec 30 even in -stringFromDate: and that is not what I want. That is a date of a real paper document and if the document was marked with Dec 31 then that is the date of the document, wherever observer may found himself.

    What should I do to store dates that are stable across time zones?
  2. balamw Moderator


    Staff Member

    Aug 16, 2005
    New England
    Store it as GMT at 00:00:00? (and of course interpret it in GMT).

  3. PhoneyDeveloper macrumors 68040


    Sep 2, 2008
  4. idelovski thread starter macrumors regular

    Sep 11, 2008
  5. North Bronson macrumors 6502

    Oct 31, 2007
    San José
    You will have some issues with NSDateComponents in certain circumstances. For example:

    In Los Angeles, at 2:00 AM on 7 November 2010, the clocks fell back to 1:00 AM. There were "two different" 1:30 AMs. One wall time gives you two system times. If you generate with NSDateComponents, it is undefined which system time the NSDateComponents correspond to.

    For 99 percent of the time, NSDateComponents works perfectly. There are a few corner cases (like daylight savings time) that can make trouble.

Share This Page