0

I need to convert my NSString in the end to an NSDate but I am having problems doing so. How would I achieve the same functionality with this code while making the end result an NSDate?

//Date and Format it
NSDate *now = [NSDate date];
NSDateFormatter* formatter = [[[NSDateFormatter alloc] init] autorelease];
[formatter setDateFormat:@"MM-dd-yyyy"];
NSString *dateString = [formatter stringFromDate:now];

Thanks!

Edit:

//Date and Format it
    NSDate *now = [NSDate date];
    NSDateFormatter* formatter = [[[NSDateFormatter alloc] init] autorelease];
    [formatter setDateFormat:@"MM-dd-yyyy"];
    NSString *dateString = [formatter stringFromDate:now];
    NSDate *enddate = [formatter dateFromString:dateString];
    [[NSUserDefaults standardUserDefaults] setObject:enddate forKey:@"theDate"];
SimplyKiwi
  • 12,376
  • 22
  • 105
  • 191

1 Answers1

3
NSDate *date = [formatter dateFromString:dateString];
Alexsander Akers
  • 15,967
  • 12
  • 58
  • 83
  • Thanks, is edit1 in my original post what I am supposed to do? – SimplyKiwi Aug 22 '11 at 23:02
  • 1
    Well it seems pretty redundant now. You're creating a date set to now, then converting it to a string, then back to a date. In theory, `now` and `enddate` should be equal. Why are you doing it like this? – Alexsander Akers Aug 23 '11 at 01:59
  • not sure. What should the code look like instead? I understand what you are saying but I am not sure how to apply it to the code. – SimplyKiwi Aug 23 '11 at 02:57
  • 1
    Well it looks like you want to store the current date and time in the user defaults. Something like this should work: `[[NSUserDefaults standardUserDefaults] setObject: [NSDate date] forKey: @"theDate"];` – Alexsander Akers Aug 23 '11 at 20:14