create a NSDate from a string create a NSDate from a string ios ios

create a NSDate from a string


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);


Your formatter is wrong. According to the NSDateFormatter documentation it should be "MM/dd/yyyy h:mm a". You also probably want to set the locale as stated in the Date Formatting Guideline:

If you're working with fixed-format dates, you should first set the locale of the date formatter to something appropriate for your fixed format. In most cases the best locale to choose is en_US_POSIX, a locale that's specifically designed to yield US English results regardless of both user and system preferences.

Try this:

NSString *str = @"3/15/2012 9:15 AM";NSLocale *enUSPOSIXLocale = [[[NSLocale alloc] initWithLocaleIdentifier:@"en_US_POSIX"] autorelease];NSDateFormatter *formatter = [[NSDateFormatter alloc]init];[formatter setLocale:enUSPOSIXLocale];[formatter setDateFormat:@"MM/dd/yyyy h:mm a"];NSDate *date = [formatter dateFromString:str];NSLog(@"%@",date);

Outputs:

2012-03-19 12:37:27.531 Untitled[6554:707] 2012-03-15 08:15:00 +0000


Hmmm - you've gone wrong for a couple of reasons

  1. the NSDateFormatter is strict and you have not been.
  2. you didn't supply str to dateFromString:
NSString* str = @"3/15/2012 9:15 PM";NSDateFormatter* formatter = [[NSDateFormatter alloc]init];[formatter setDateFormat:@"MM/dd/yyyy HH:mm a"];NSDate* date = [formatter dateFromString:str];NSLog(@"%@",date);


matomo