Some tips with NSDate

/
0 Comments
When doing my project, I want to create an NSDate object is 7 days before the current date. At the moment it makes me crazy haha :D. Now I want to share my workshop code to everyone which meet the problem as me. :P

- First of all, I create 2 methods. The first one is create a custom nsdate object from day, month, year and the second one is parse current date to 3 elements (day, month, year).

Utilities.m

 
+ (NSDate *)createCustomDateFromDay:(NSInteger)_day month:(NSInteger)_month year:(NSInteger)_year
{
    NSCalendar *gregorian = [[NSCalendar alloc] initWithCalendarIdentifier:NSGregorianCalendar];
    NSDateComponents *comps = [[NSDateComponents alloc] init];
    [comps setDay:_day];
    [comps setMonth:_month];
    [comps setYear:_year];
    NSDate *date = [[gregorian dateFromComponents:[comps autorelease]] autorelease];
    return date;
}

+ (void)currentDay:(int *)_day month:(int *)_month year:(int *)_year
{
    NSDate *curentDate = [NSDate date];
    NSCalendar* calendar = [NSCalendar currentCalendar];
    NSDateComponents* compoNents = [calendar components:NSYearCalendarUnit|NSMonthCalendarUnit|NSWeekCalendarUnit|NSWeekdayCalendarUnit fromDate:curentDate]; // Get necessary date components
    compoNents = [calendar components:NSYearCalendarUnit|NSMonthCalendarUnit|NSWeekCalendarUnit|NSWeekdayCalendarUnit|NSDayCalendarUnit fromDate:curentDate]; 
    *_month = [compoNents month]; 
    *_day = [compoNents day]; 
    *_year = [compoNents year]; 
}

In the any .m class, I call these functions
int day = 0, month = 0, year = 0;
[Utilities currentDay:&day month:&month year:&year];
NSLog(@"%d %d %d", day, month, year);

After that, create your custom date
[Utilities createCustomDateFromDay:day+1 month:month+1 year:year];

Please note that, you must verify day, month.


You may also like

No comments:

Member of Mroom Software. Powered by Blogger.