formatting date returns (null)

Discussion in 'Mac Programming' started by johnmerlino, Dec 4, 2011.

  1. johnmerlino macrumors member

    Oct 22, 2011
    Hey all,

    I have a date stored in a postgres database with a time data type. When I send it to objective-c, if I just put it in a field as is, then the field will contain this:


    I would like that to be formatted better, so I do this:

           NSDateFormatter *formatter;
            NSString        *dateString;
            NSDate *date = report.time;
            formatter = [[NSDateFormatter alloc] init];
            [formatter setDateFormat:@"dd-MM-yyyy HH:mm"];
            dateString = [formatter stringFromDate:date];
            timeTextField.text = [NSString stringWithFormat:@"%@", dateString];
    But when I do the above, it converts the date into (null).

    thanks for response
  2. chown33 macrumors 604

    Aug 9, 2009
    Sailing beyond the sunset
    Apply basic debugging skills.
    1. Break It Down.
    2. Confirm Expectations.

    Break It Down means breaking the problem into sub-problems. The conversion isn't monolithic; it consists of logical sub-parts. Each statement in your original code can have its result confirmed.

    Confirm Expectations means testing whether report.time is a) non-nil, and b) of type NSDate.

    Example code:
    #import <Foundation/Foundation.h>
    int main(int arcgc, char *argv[])
    	NSAutoreleasePool * pool = [[NSAutoreleasePool alloc] init];
    	NSDate *date = [NSDate date];  // EXAMPLE ONLY: current date/time
    	NSLog( @"date: %@, class: %@", date, NSStringFromClass( [date class] ) ); 
    	[NSDateFormatter setDefaultFormatterBehavior: NSDateFormatterBehavior10_4];  // confirm desired behavior will result
    	NSDateFormatter * f = [[NSDateFormatter alloc] init];
    	[f setDateFormat:@"dd-MM-yyyy HH:mm"];
    	NSString * s = [f stringFromDate:date];
    	NSLog( @"text: %@", s ); 
    	[pool drain];
    	return 0;
    The red-hilited code is redundant and unnecessary. dateString is already an immutable string. You don't need another copy of it. Use it as-is.
  3. johnmerlino thread starter macrumors member

    Oct 22, 2011

Share This Page