views:

1648

answers:

4

Hi,

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 a 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?

Thanks in advance!

A: 

I would try to set up an NSDateFormatter to successfully parse the string by the following method:

- (NSDate *)dateFromString:(NSString *)string

Note that it could take you a while to get the NSDateFormatter set up just right to successfully parse your string.

If you're going to store program-facing data like this I would also recommend storing it in an easier-to-access format, e.g., CFAbsoluteTime. Once you have it in your program you can format it into the international format or something else human-readable.

fbrereto
+2  A: 

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.

Jeff Kelley
A: 

Convert it to a format NSDate accepts and then perform the conversion back.

Alternatively, depending on which NSDate you're referring to (!) initWithString should cover international standard dates.

Rushyo
+5  A: 

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]];
Daniel Rinser
Yes, I need cross-platform exchangeable date strings. This should solve it. Thank you!
Jongsma