Monday, May 23, 2011

NSCalendar components fromDate example objc

NSCalendar components:fromDate: method is used to convert a NSDate object into YY/MM/DD/HH/MM/SS format. It returns an object of NSDateComponents type. The conversion is performed only through the calendar object (It's very natural. Different calendar system outputs different yy/mm/dd and so on). An Example of NSCalendar components:fromDate: is shown below. Components takes BitMasks which specifies which components of the date will be extracted. [NSCaldendar components:fromDate: example]


Declaration.


- (NSDateComponents *)components:(NSUInteger)unitFlags fromDate:(NSDate *)date
Parameters
unitFlags
The components into which to decompose date—a bitwise OR of NSCalendarUnit constants.
[List of NSCalendar Calendar Units
 
// Following list is quoted from Apple Developer Site.
//
enum {
   NSEraCalendarUnit = kCFCalendarUnitEra,
   NSYearCalendarUnit = kCFCalendarUnitYear,
   NSMonthCalendarUnit = kCFCalendarUnitMonth,
   NSDayCalendarUnit = kCFCalendarUnitDay,
   NSHourCalendarUnit = kCFCalendarUnitHour,
   NSMinuteCalendarUnit = kCFCalendarUnitMinute,
   NSSecondCalendarUnit = kCFCalendarUnitSecond,
   NSWeekCalendarUnit = kCFCalendarUnitWeek,
   NSWeekdayCalendarUnit = kCFCalendarUnitWeekday,
   NSWeekdayOrdinalCalendarUnit = kCFCalendarUnitWeekdayOrdinal
   NSQuarterCalendarUnit = kCFCalendarUnitQuarter,
};
typedef NSUInteger NSCalendarUnit;
 
date
The date for which to perform the calculation.
[Example]

  // Get current date and translate it into YY/MM/DD format.
  //
    NSDate              *today = [NSDate date];
    NSCalendar          *calendar = [NSCalendar currentCalendar];
    NSDateComponents    *todayComp = [calendar components:(NSYearCalendarUnit | NSMonthCalendarUnit | NSDayCalendarUnit) fromDate:today];