Mac formatting date returns (null)

johnmerlino

macrumors member
Original poster
Oct 22, 2011
81
0
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
 

chown33

Moderator
Staff member
Aug 9, 2009
8,779
5,159
vertical
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;
}
Code:
        timeTextField.text = [COLOR="Red"][NSString stringWithFormat:@"%@",[/COLOR] dateString];
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.
 
Register on MacRumors! This sidebar will go away, and you'll see fewer ads.