Reputation: 51
I have a varchar in mysql that holds dates. I have been trying to convert it into an NSDate
, but nothing I have tried yet works. The NSString
from mysql looks like this:
August 11, 2012, 10:17 AM
All the posts so far relating to NSString
to NSDate
conversions have not yet worked for this string. If someone could please help...
Upvotes: 1
Views: 2186
Reputation: 24031
to convert a NSString
into a NSDate
, please, use the NSDateFormatter
.
NSString *_dateString = @"August 11, 2012, 10:17 AM";
NSDateFormatter *_dateFormatter = [[NSDateFormatter alloc] init];
[_dateFormatter setDateFormat:@"MMMM dd, yyyy, HH:mm a"];
NSDate *_date = [_dateFormatter dateFromString:_dateString];
NSLog(@"raw date : %@", _date);
NSLog(@"formatted date : %@", [_dateFormatter stringFromDate:_date]);
the output NSDate
will contains the date:
raw date : 2012-08-10 23:17:00 +0000
formatted date : August 11, 2012, 11:17 AM
you can format the NSDate
as you'd like for a different output, it is up to up now, but you can work with the NSDate
object which contains the date.
NOTE: we don't know the timezone from the input date when we are converting it, so the NSDate
using the defaults for it. if you set the current timezone you will get the correct date after conversion.
Upvotes: 2
Reputation: 2210
I assume you use JSON for getting data from MySQL(server) and have a JSON object called myJSONObject
NOTE:
myJSONObject
must be serialized using some framework like NSJSONSerialization
EDIT with some detailed question links
You have asked to convert data to August 11, 2012, 10:17 AM but my sample code tries to convert as 2012-08-11 10:17:.., i edited my sample code for you. For more, take a look at NSDateFormatter
ATTENTION PLEASE: you can get the variable month_from_date
using NSDateComponents. There are some questions about it here and here.. If you can't, please open a new post.
NSString* dateString = [myJSONObject objectForKey:@"date"];
NSDateFormatter* fmt = [NSDateFormatter new];
[fmt setTimeZone:[NSTimeZone defaultTimeZone]];
// [fmt setDateFormat:@"yyyy-MM-dd HH:mm:ss"];
[fmt setDateFormat:@"%@ DD,YYYY, HH:mm",month_from_date];
NSDate* dateFromString = [fmt dateFromString:dateString];
NSLog("Here is date from string: %@",dateFromString);
Upvotes: 2