Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Convert an NSDate's description into an NSDate?

I store my NSDates to a file in the international format you get when you call description on a NSDate.

However, I don't know how to go back from the string-format to an NSDate object. NSDateFormatter seems to be limited to a couple of formats not including the international one.

How should I go back from the string-format?

like image 835
Pieter Jongsma Avatar asked Aug 28 '09 20:08

Pieter Jongsma


2 Answers

Jeff is right, NSCoding is probably the preferred way to serialize NSDate objects. Anyways, if your really want/need to save the date as a plain date string this might help you:

Actually, NSDateFormatter isn't limited to the predefined formats at all. You can set an arbitrary custom format via the dateFormat property. The following code should be able to parse date strings in the "international format", ie. the format NSDate's -description uses:

NSDateFormatter* dateFormatter = [[[NSDateFormatter alloc] init] autorelease];
dateFormatter.dateFormat = @"yyyy-MM-dd HH:mm:ss ZZZ";
NSDate* date = [dateFormatter dateFromString:@"2001-03-24 10:45:32 +0600"];

For a full reference on the format string syntax, have a look at the Unicode standard.

However, be careful with -description - the output of these methods is usually targeted to human readers (eg. log messages) and it is not guaranteed that it won't change its output format in a new SDK version! You should rather use the same date formatter to serialize your date object:

NSDateFormatter* dateFormatter = [[[NSDateFormatter alloc] init] autorelease];
dateFormatter.dateFormat = @"yyyy-MM-dd HH:mm:ss ZZZ";
NSString* dateString = [dateFormatter stringFromDate:[NSDate date]];
like image 144
Daniel Rinser Avatar answered Oct 23 '22 10:10

Daniel Rinser


Instead of saving the description to a file, why not save the object itself? NSDate conforms to the NSCoding protocol; saving the object means you don't have to worry about translating it. See the NSCoding protocol reference for more information.

like image 35
Jeff Kelley Avatar answered Oct 23 '22 08:10

Jeff Kelley