Use NSDateFormatter
with a dateFormat
string. If you want that yyyy-mm-dd format, use yyyy-MM-dd HH:mm:ss Z
(note the capital MM
for month and HH
for hour):
NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
formatter.timeZone = [NSTimeZone timeZoneWithName:@"GMT"];
formatter.dateFormat = @"yyyy-MM-dd HH:mm:ss Z";
formatter.locale = [NSLocale localeWithLocaleIdentifier:@"en_US"];
_postTime.text = [formatter stringFromDate:picker.date];
If you want that 21st March 2014, 6:30pm format in your local timezone, you can use something like:
NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
formatter.dateFormat = @"d MMMM yyyy, hh:mma";
formatter.locale = [NSLocale localeWithLocaleIdentifier:@"en_US"];
_postTime.text = [formatter stringFromDate:picker.date];
If you want to format that date in the format specified by the user's device (which is a nice way to present date/time, respectful of the user's preferences in settings):
NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
formatter.dateStyle = NSDateFormatterLongStyle;
formatter.timeStyle = NSDateFormatterShortStyle;
_postTime.text = [formatter stringFromDate:picker.date];
Refer to the NSDateFormatter Class Reference or the Date Formatters section of the Data Formatting Guide for more information. The date formatter gives you a great deal of control over how you want the date formatted.