I am receiving the following date in string format from the API
2015-04-18 06:08:28.000000
I want the date to be in the format of d/M/yyyy
I tried the following
NSString *datevalue = (NSString*)value;
NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
[formatter setDateFormat:@"d/M/yyyy"];
NSDate *date = [formatter dateFromString:datevalue];
NSString *currentDate = [formatter stringFromDate:date];
This returns NIL, what could be the possible issue, or how do i format such dates in objective-c?
Thanks.
You should use the yyyy-MM-dd HH:mm:ss.SSSSSSS
format string for the date formatter converting the API date into a NSDate
object, as discussed by the others. But, you also want to consider the timeZone
and locale
properties of this formatter.
Usually RFC 3339 dates are exchanged in GMT. Confirm this with your API, but it's generally GMT/UTC/Zulu. If so, you will probably also want to explicitly set the timezone:
formatter.timeZone = [NSTimeZone timeZoneForSecondsFromGMT:0];
But confirm what timezone the API expects.
A more subtle issue is the handling users with non-Gregorian calendars
formatter.locale = [[NSLocale alloc] initWithLocaleIdentifier:@"en_US_POSIX"];
For more information, see Apple Technical Q&A 1480.
Clearly, these dateFormat
, timeZone
, and locale
properties are simply for converting the API date string into a NSDate
object. When then outputting the date for the end user, you would use a separate formatter, defaulting to the standard timeZone
and locale
properties and use whatever dateFormat
string you want for the output. (Frankly, I wouldn't generally advise using dateFormat
string for user output formatters, but rather just use the appropriate values for the dateStyle
and timeStyle
properties.)