create a NSDate from a string

[亡魂溺海] 提交于 2019-11-30 04:31:44
Ilanchezhian

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);
  NSString *str =@"3/15/2012 9:15 PM";
NSDateFormatter *dateformatter = [[NSDateFormatter alloc]init];
   [dateformatter setDateFormat:@"MM/dd/yyyy"];
NSArray *firstSplit = [str componentsSeparatedByString:@" "];
NSDate *dateSelected = [dateformatter dateFromString:[firstSplit objectAtIndex:0]];

    [dateformatter setDateFormat:@"mm:ss"];
NSDate *dateSelected2 = [dateformatter dateFromString:[firstSplit objectAtIndex:1]];
NSLog(@"%@",[dateformatter stringFromDate:dateSelected2]);

NSLog(@"%@",[dateformatter stringFromDate:dateSelected]);
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!