Reputation: 83
i came across a problem in my iPhone application.
in my app i converte time string to date like that
NSString *time = @"01:30 PM";
NSDateFormatter *dateFormat = [[NSDateFormatter alloc] init];
[dateFormat setDateFormat:@"hh:mm a"];
NSDate *date = [dateFormat dateFromString:time];
and for some reason always date
is nil after [dateFormat dateFromString:time]
.
can anyone tell me what i'm doing wrong?
thanks
Upvotes: 2
Views: 757
Reputation: 2451
try this...
NSString *time = @"01:30 pm";
NSDateFormatter *dateFormat = [[NSDateFormatter alloc] init];
[dateFormat setTimeStyle:NSDateFormatterShortStyle];
[dateFormat setDateFormat:@"hh:mm a"];
dateFormat.timeZone = [NSTimeZone timeZoneWithName:@"GMT"];
NSDate *date = [dateFormat dateFromString:time];
NSLog(@"date %@",[dateFormat stringFromDate:date]);
Upvotes: 1
Reputation: 825
I'm assuming your device language is other then English. In that case you need to set the date formatter Locale. Try this code.
NSString *time = @"01:30 PM";
NSDateFormatter *dateFormat = [[NSDateFormatter alloc] init];
[dateFormat setDateFormat:@"hh:mm a"];
[dateFormat setLocale:[[NSLocale alloc] initWithLocaleIdentifier:@"en_US_POSIX"]];
Upvotes: 2
Reputation: 1261
NSString *dats1 = @"01:30:00 PM";
NSDateFormatter *dateFormatter1 = [[NSDateFormatter alloc] init] ;
[dateFormatter1 setDateStyle:NSDateFormatterMediumStyle];
[dateFormatter1 setDateFormat:@"HH:mm:ss"];
NSDate *date = [dateFormatter1 dateFromString:dats1];
NSLog(@"date : %@", date);
NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
[formatter setDateFormat:@"hh:mm a"];
NSLog(@"Current Date: %@", [formatter stringFromDate:date]);
Upvotes: 0