Question

I've been at this for a while, browsing all the forums for help, but I just can't get this to work. I'm new to xcode and i'm trying to change yyyy-mm-dd hh:mm:ss +0000 into e.g 21st March 2014, 6:30pm. My current code is:

-(void)viewDidLoad{
UIDatePicker *datePicker = [[UIDatePicker alloc]init];

[datePicker setDate:[NSDate date]];
[datePicker addTarget:self action:@selector(updateTextField:) forControlEvents:UIControlEventValueChanged];
[_postTime setInputView:datePicker];
}

-(void)updateTextField:(id)sender{
if([_postTime isFirstResponder]){
    UIDatePicker *picker = (UIDatePicker*)_postTime.inputView;
    _postTime.text = [NSString stringWithFormat:@"%@",picker.date];
}
}

I'd appreciate all the help I can get.

Thanks

Was it helpful?

Solution

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.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top