Convert NSDate description to NSDate?

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

However, I do not know how to return from a string format to an NSDate object. NSDateFormatter seems to be limited to several formats, not including international.

How do I return from a string format?

+6
date serialization iphone nsdate
source share
4 answers

Jeff is right, NSCoding is probably the preferred way to serialize NSDate objects. Anyway, if you really want / want to save the date as a simple date string, this can help you:

Actually, NSDateFormatter not limited to predefined formats. You can set an arbitrary arbitrary format using the dateFormat property. The following code should be able to parse date strings in an "international format", i.e. NSDate -description format 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 complete reference to the format string syntax, check out the Unicode standard .

However, be careful with -description - the output of these methods is usually aimed at people readers (for example, log messages), and it is not guaranteed that it will not change its output format in the new version of the SDK! You must use the same date format 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]]; 
+25
source share

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

+4
source share

I would try to configure NSDateFormatter to successfully parse a string in the following way:

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

Please note that it may take some time for you to configure NSDateFormatter correctly in order to successfully NSDateFormatter your string.

If you intend to store data accessing the program, I would also recommend storing it in a more convenient format for access, for example CFAbsoluteTime . After you purchase it in your program, you can format it in an international format or something else that can be read on a person.

0
source share

Convert it to the format that NSDate accepts and then performs the conversion.

Alternatively, depending on what NSDate you mean (!), InitWithString should cover international standards dates.

0
source share

All Articles