Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

create a NSDate from a string

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.

like image 635
samir Avatar asked Mar 19 '12 11:03

samir


People also ask

How to create NSDate from string?

dateFormat = @"MM/dd/yyyy HH:mm a"; NSDate *date = [formatter dateFromString:str]; NSLog(@"%@", date);

What is NSDate?

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.

Is NSDateFormatter thread safe?

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.


1 Answers

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); 
like image 92
Ilanchezhian Avatar answered Oct 09 '22 22:10

Ilanchezhian