简体   繁体   中英

How to convert NSString to NSDate?

I want to search my Array of Dictionary for particular date.Ex I want to search my array of dictionary for date "16 Jan 2012" which is in string format but my dictionary item in array contains date and time, say "16 Jan 2012 somehours:somemins:somesecs" .I am converting string format date in NSDate format but I am getting date as 2012-01-15 18:30:00 +0000 instead of 2012-01-16 .I am using NSPredicate to search for the date which convert date into seconds as follows "Date == CAST(348345000.000000, "NSDate")" and compare so even though my records contain date as "16 Jan 2012 somehours:somemins:somesecs" it will not satisfied the criteria.I want that the records/array containing date as "16 Jan 2012 somehours:somemins:somesecs" should satisfied the search criteria.Please can anyone know how to achieve this?

Thanks in advance!

You need to use NSDateFormatters to convert the date string from one format to another. You can have an inputDateFormatter where you use dateFromString to give you an NSDate, and then feed this into an outputDateFormatter which gives your desired string.

NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
[dateFormatter setDateFormat:@"dd MMM yyyy"];
NSString *dateInFormatYouWant = [dateFormatter stringFromDate:yourDate]

I'm not sure if there is a more efficient way of doing it than this.

To rid yourself of NSDateFormatter 's automatic adjustment for your time zone use something like this.

dateFormatter.timeZone = [NSTimeZone timeZoneForSecondsFromGMT:0];

To elaborate; " 16 Jan 2012 " Contains no hour, minute, or seconds value, so when parsing it with an NSDateFormatter one would expect an NSDate with a description of " 2012-01-16 00:00:00 +000 " But that's not what you're getting because the date formatter is adjusting for the 5:30 Hours between GMT and India?(Assuming based on :30 differential). By setting the date formatter's time zone explicitly you avoid this problem.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM