1. Welcome to the new MacRumors forums. See our announcement and read our FAQ

formatting date returns (null)

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

  1. macrumors member

    #1
    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:

    2011-05-10T09:49:00Z

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

    Code:
           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. macrumors 603

    #2
    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:
    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. macrumors member

    #3
    thanks for response
     

Share This Page