I have an NSString
like this: @"3/15/2012 9:15 PM"
and I would like to convert it to NSDate
, I have done like this:
NSString *str =@"3/15/2012 9:15 PM"; NSDateFormatter *formatter = [[NSDateFormatter alloc]init]; [formatter setDateFormat:@"mm/dd/yyyy HH:mm"]; NSDate *date = [formatter dateFromString:]; NSLog(@"%@", date); // date = null
Can you help me please, thanks.
dateFormat = @"MM/dd/yyyy HH:mm a"; NSDate *date = [formatter dateFromString:str]; NSLog(@"%@", date);
The NSDate class provides methods for comparing dates, calculating the time interval between two dates, and creating a new date from a time interval relative to another date.
Thread Safety On earlier versions of the operating system, or when using the legacy formatter behavior or running in 32-bit in macOS, NSDateFormatter is not thread safe, and you therefore must not mutate a date formatter simultaneously from multiple threads.
Use the following solution
NSString *str = @"3/15/2012 9:15 PM"; NSDateFormatter *formatter = [[NSDateFormatter alloc] init]; formatter.dateFormat = @"MM/dd/yyyy HH:mm a"; NSDate *date = [formatter dateFromString:str]; NSLog(@"%@", date);
Edit: Sorry, the format should be as follows:
formatter.dateFormat = @"MM/dd/yyyy hh:mm a";
And the time shown will be GMT time. So if you add/subtract the timezone, it would be 9:15 PM.
Edit: #2
Use as below. You would get exact time too.
NSString *str = @"3/15/2012 9:15 PM"; NSDateFormatter *formatter = [[NSDateFormatter alloc] init]; formatter.dateFormat = @"MM/dd/yyyy hh:mm a"; NSTimeZone *gmt = [NSTimeZone timeZoneWithAbbreviation:@"GMT"]; formatter.timeZone = gmt; NSDate *date = [formatter dateFromString:str]; NSLog(@"%@",date);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With