Reputation: 3240
I want to get NSDate from NSString. My code:
NSDateFormatter *dateFormatter = [NSDateFormatter new];
[dateFormatter setDateFormat:@"yyyy-MM-dd HH:mm:ss"];
NSDate *date = [dateFormatter dateFromString:@"2016-05-05 09:29:31"];
NSLog(@"date %@",date);
And I see in console:
date (null)
What is wrong with my date format? Thank you.
Upvotes: 1
Views: 600
Reputation: 4855
Your code is correct.
If the device is set to AM/PM time and requested string format is set to @"yyyy-MM-dd HH:mm:ss" dateFromString will return nil. Try setting the locale like :
[dateFormatter setLocale:[[NSLocale alloc] initWithLocaleIdentifier:@"en_US"]];
Upvotes: 6
Reputation: 118
You can also use my code for getting NSDate from NSString for any kind of format you want.
Below is my code :
- (NSDate *)dateFromString:(NSString *)stringDate withFormat:(NSString *)format {
NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
formatter.dateFormat = format;
NSDate *dateFromString = [formatter dateFromString:stringDate];
return dateFromString; }
Upvotes: 1
Reputation: 63
try this code
NSString *dateString = @"05-05-2016 09:29:31";
NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
// if format doesn't match you'll get nil from your string, so be careful
[dateFormatter setDateFormat:@"dd-MM-yyyy HH:mm:ss"];
NSDate *dateFromString = [[NSDate alloc] init];
dateFromString = [dateFormatter dateFromString:dateString];
Upvotes: 1
Reputation: 4096
Use below code ..
NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
[dateFormatter setDateFormat:@"yyyy-MM-dd hh:mm:ss"];
NSString *date_time = [dateFormatter stringFromDate:[NSDate date]];
Hope this is useful
Upvotes: 0
Reputation: 82786
I tried your question
NSDateFormatter *dateFormatter = [NSDateFormatter new];
[dateFormatter setDateFormat:@"yyyy-MM-dd HH:mm:ss"];
NSDate *date = [dateFormatter dateFromString:@"2016-05-05 09:29:31"];
NSLog(@"newDate : %@",date);
I got the output like
Upvotes: 1