简体   繁体   English

如何将NSString转换为NSDate?

[英]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? 我想在字典数组中搜索特定的date.Ex,我想在字典数组中搜索日期"16 Jan 2012" ,该日期是字符串格式,但我的字典项中包含日期和时间,例如"16 Jan 2012 somehours:somemins:somesecs" 。我正在以NSDate格式转换字符串格式的日期,但我将日期设置为2012-01-15 18:30:00 +0000而不是2012-01-16 。我正在使用NSPredicate搜索日期它将日期转换为秒,如下所示: "Date == CAST(348345000.000000, "NSDate")"并进行比较,因此即使我的记录包含日期为"16 Jan 2012 somehours:somemins:somesecs"它也不满足该条件。我想要包含日期为"16 Jan 2012 somehours:somemins:somesecs"的记录/数组应满足搜索条件。请问有人知道如何实现此目标吗?

Thanks in advance! 提前致谢!

You need to use NSDateFormatters to convert the date string from one format to another. 您需要使用NSDateFormatters将日期字符串从一种格式转换为另一种格式。 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. 您可以拥有一个inputDateFormatter,在其中使用dateFromString为您提供一个NSDate,然后将其输入到outputDateFormatter中,从而提供您想要的字符串。

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. 要摆脱NSDateFormatter对您所在时区的自动调整,请使用类似以下的内容。

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). 16 Jan 2012 ”不包含小时,分钟或秒的值,因此使用NSDateFormatter对其进行解析时,会期望使用描述为“ 2012-01-16 00:00:00 +000 ”的NSDate,但这不是您所需要的是因为日期格式器正在针对格林尼治标准时间和印度之间的5:30小时进行调整?(假设基于:30时差)。 By setting the date formatter's time zone explicitly you avoid this problem. 通过显式设置日期格式程序的时区,可以避免此问题。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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