Lacrifilm Lacrifilm - 1 year ago 131
iOS Question

NSDateFormatterLongStyle string to NSDate

I have a UIDataPicker in my viewController with default location, when my user finishes selecting the date I run this code:

NSString *dateString = [NSDateFormatter localizedStringFromDate:[self.dataPicker date]

With that code I can storage the date in the following format:

May 31, 2016

Later in my code I need to convert this string into a real date format, for this I use the code below:

NSString *dateString = date;
NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
dateFormatter.locale = [[NSLocale alloc] initWithLocaleIdentifier:@"en_US"];
[dateFormatter setDateFormat:@"MM/dd/yyyy"];

return [dateFormatter dateFromString:dateString];

But this code return a null value. As the datepicker is set by default, my system can receive any date format, but in the end I want it to be converted to the format en_us.

How I can solve this problem?

Answer Source

Don't store the date as a string; store it as an offset, in seconds, from some reference date.


uint64_t offset = (uint64_t)[[self.dataPicker date] timeIntervalSinceReferenceDate];
// store this 64-bit unsigned integer.

This takes less space and is quicker to convert to/from an NSDate object.

You can leave the offset as an NSTimeInterval (64-bit floating point double) if you prefer, but as you aren't storing date & time, uint64_t should do...

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download