Reputation: 148
I need to convert an NSString to an NSDate, but the following code only works as long as the user's device isn't set to 24-Hour time.
NSDateFormatter *formatter = [[NSDateFormatter alloc]init];
[formatter setDateFormat:@"MM/dd/yyyy hh:mm:ss a"];
NSString *aTime = @"2/11/2013 12:00:00 AM";
NSDate *aDate = [formatter dateFromString:aTime];
However, aDate returns null when the device is in 24-Hour time. Any help?
Upvotes: 2
Views: 1377
Reputation: 1750
try this code
NSString *string = @"2015-11-30 15:00:00";
NSDateFormatter* formatter = [[NSDateFormatter alloc] init];
formatter.dateFormat = @"yyyy-MM-dd HH:mm:ss";
[formatter setTimeZone:[NSTimeZone localTimeZone]];
NSDate *date = [formatter dateFromString:string];
date: 2015-11-29 21:30:00 +0000
its in UTC format you can modify this as you need!
Upvotes: 0
Reputation: 11
I think the following snippet might helps you out.
NSString *dateString = @"09:34 AM";
NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
dateFormatter.dateFormat = @"dd-MM-yyyy";
NSString *stringFromDate = [dateFormatter stringFromDate:[NSDate date]];
dateFormatter.dateFormat = @"dd-MM-yyyy hh:mm a";
dateFormatter.locale = [[NSLocale alloc] initWithLocaleIdentifier:@"en_US_POSIX"];
NSDate *returnDate = [dateFormatter dateFromString:[NSString stringWithFormat:@"%@ %@", stringFromDate, dateString]];
Upvotes: 1
Reputation: 100632
I think you're probably seeing a side effect of the behaviour described by QA1480. Apple has resolved what it presumably thought was developers not obeying locales properly by modifying your prescribed date format unless you explicitly say not to.
You can achieve that by adding:
formatter.locale = [[NSLocale alloc] initWithLocaleIdentifier:@"en_US_POSIX"];
/* and autorelease if not using ARC */
Which basically says 'the date format I just set is explicitly what I want, please don't modify it in any way'.
Upvotes: 8