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?
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]];
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With