I try to get NSDate objects from NSString which I get from sqlite, but there is a time problem. I takes me 130ms every time.开发者_如何学C And it's insufferable for i have two hundred objects to deal with. So can somebody tell me what i should do. Thanks.
Assuming you're using NSDateFormatter
, you should attend to Apple's recommendation, caching formatters for efficiency. Instead of creating a NSDateFormatter
each time you want to convert a date, you should keep a single instance of your NSDateFormatter
. From Data Formatting guide:
Cache Formatters for Efficiency
Creating a date formatter is not a cheap operation. If you are likely to use a formatter frequently, it is typically more efficient to cache a single instance than to create and dispose of multiple instances. One approach is to use a static variable.
NSDateFormatter *formatter=[[NSDateFormatter alloc] init];
[formatter setDateFormat:@"HH:mm:ss:SSS"];
NSDate *currentdate=[formatter dateFromString:currentdateStr];
//it returns DateObject If String in Specified Format otherwise Returns nil;
I think this code block will help you :
NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
[dateFormatter setDateFormat:@"<Add Your Date Format>"];
NSCalendar *calendar = [[NSCalendar alloc] initWithCalendarIdentifier:NSGregorianCalendar];
NSDateComponents *dateComponent = [calendar components:NSYearCalendarUnit
|NSMonthCalendarUnit
|NSDayCalendarUnit
fromDate:[dateFormatter dateFromString: <Add Your Date String> ]];
[dateComponent setHour:24];
[dateComponent setMinute:00];
[dateComponent setSecond:00];
<Your NSDate Object> = [calendar dateFromComponents:dateComponent];
It might require to change dateComponent values for Hour, Minute, Seconds - according to your calendar time.
Let me know if you face any problem in this..
精彩评论