Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

NSString to NSDate and then changing the format

I thought I had the "hard" part done but that doesn't seem to be the case. I retrieve a date from an RSS feed that I would like to convert to a NSDate and then change it to the simple format (MM/DD/YYYY). The date comes in this format on the RSS feed:

Thu, 1 Nov 2012 17:41:56 CST

I have converted it to an NSDate successfully.

NSDateFormatter *df = [[NSDateFormatter alloc] init];
[df setDateFormat:@"E, d MMM yyyy HH:mm:ss zzz"];
NSDate *date = [[NSDate alloc] init];
//[df setDateStyle:NSDateFormatterMediumStyle]; Using these seems to change what it expects from the string I guess?
//[df setTimeStyle:NSDateFormatterMediumStyle];
date = [df dateFromString:string];
[self.tempItem setPubDate:[df dateFromString:string]];
NSLog(@"%@", [df dateFromString:string]);

So I get my date just fine, but like I said before I want to just convert it to a simple date. When I use setDateStyle I end up with null values. When I don't use it, I get correct dates, just not in the format I want it to end up being.

like image 371
Doug Avatar asked Dec 05 '25 12:12

Doug


2 Answers

just not in the format I want it to end up being.

Because NSLog() doesn't know about the format - how would it? NSDate doesn't have any built-in "format". You have to obtain a string from the date object by using NSDateFormatter once again. Basically the workflow you'll have to use is roughly:

  • retrieve an NSString from the RSS feed
  • Create a date formatter
  • Set its format according to the format of the string
  • Get an NSDate object from the date formatter
  • Re-set the format of the NSDateFormatter to the format you desire
  • Obtain a properly formatted NSString using the date and the date formatter objects.

Just create another NSDateFormatter to convert NSDate to NSString

NSDateFormatter *dfSimple = [[NSDateFormatter alloc] init];

[dfSimple setTimeStyle:NSDateFormatterNoStyle];

[dfSimple setDateStyle:NSDateFormatterMediumStyle];

NSLog(@"%@", [dfSimple stringFromDate: date]);

It is better to create 2 NSDateFormatter objects in this case

like image 39
Vito Limandibhrata Avatar answered Dec 08 '25 16:12

Vito Limandibhrata



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!