Reputation: 11700
If I'm not interested in the time can I ignore it? I.e I have a date string that looks like this @"2012-12-19T14:00:00"
but I'm only interested in getting the date (2012-12-19) but if I set NSDateFormatter
like [dateFormatter setDateFormat:@"yyyy-MM-dd"];
it will return me a nil NSDate
.
Upvotes: 1
Views: 2027
Reputation: 52227
An NSDate object will always contain a time component as well, as it is representing a point in time — from this perspective one could argue the name NSDate is misleading.
You should create a date formatter for creating dates from string, set the time to the start of the day and use a second date formatter to output the date without time component.
NSString *dateString = @"2012-12-19T14:00:00";
NSDateFormatter *inputFormatter = [[NSDateFormatter alloc] init];
[inputFormatter setDateFormat:@"yyyy-MM-dd'T'HH:mm:ss"];
NSDateFormatter *outputFormatter = [[NSDateFormatter alloc] init];
[outputFormatter setDateStyle:NSDateFormatterShortStyle];
[outputFormatter setTimeStyle:NSDateFormatterNoStyle];
NSDate *date = [inputFormatter dateFromString:dateString];
//this will set date's time components to 00:00
[[NSCalendar currentCalendar] rangeOfUnit:NSDayCalendarUnit
startDate:&date
interval:NULL
forDate:date];
NSString *outputString = [outputFormatter stringFromDate:date];
NSLog(@"%@", outputString);
results in
19.12.12
while the format — as it is chosen by styling — will be dependent of your environment locale
Upvotes: 3
Reputation: 6524
all date string returns 10 characters for the date, what i mean is the date of todayy will be 2012-11-19
you can easily substring the date and use it as you want:
Example :
NSString* newDate = @"";
newDate = [[NSDate date]substringToIndex:10];
the out put will be : 2012-11-19
Upvotes: -2