Tuesday, May 24, 2011

NSDateFormatter stringFromDate example objc

NSDateFormatter stringFromDate returns a NSString representation of a given date formatted using the receiver’s current settings. NSDateFormatter stringFromDate takes one argument: a NSDate object. [NSDateFormatter stringFromDate example]

Declaration.

- (NSString *)stringFromDate:(NSDate *)date
Parameters
date
The date to format.
Return Value
A string representation of date formatted using the receiver’s current settings.

------------------------------------------------------------------------
[Example 1]


NSDate *today = [NSDate date];
NSDateFormatter *dateFormat = [[NSDateFormatter alloc] init];
[dateFormat setDateFormat:@"MM/dd/yyyy :EEEE"];
NSString *dateString = [dateFormat stringFromDate:today];
NSLog(@"date: %@", dateString);
[dateFormat release];
NSCalendar *gregorian = [[NSCalendar alloc] initWithCalendarIdentifier:NSGregorianCalendar];
NSDateComponents *components = [gregorian components:NSWeekdayCalendarUnit | NSYearCalendarUnit | NSMonthCalendarUnit | NSDayCalendarUnit fromDate:today];
[components setDay:([components day]-([components weekday]-1))];
NSDate *beginningOfWeek = [gregorian dateFromComponents:components];
NSDateFormatter *dateFormat_first = [[NSDateFormatter alloc] init];
[dateFormat_first setDateFormat:@"MM/dd/yyyy :EEEE"];
NSString *dateString_first = [dateFormat_first stringFromDate:beginningOfWeek];
NSLog(@"First_date: %@", dateString_first);