View Full Version : formatting date returns (null)

Dec 4, 2011, 02:55 PM
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

Dec 4, 2011, 04:52 PM
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;

timeTextField.text = [NSString stringWithFormat:@"%@", 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.

Dec 7, 2011, 02:38 PM
thanks for response