使用 NSDate 创建事件
Posted
技术标签:
【中文标题】使用 NSDate 创建事件【英文标题】:Create Event with NSDate 【发布时间】:2011-02-18 10:10:49 【问题描述】:有没有办法为 NSDate 创建事件?这是我的代码
NSDate *date = [NSDate date];
NSDateFormatter *dateFormatter = [[[NSDateFormatter alloc] init] autorelease];
[dateFormatter setDateFormat:@"MMMM d, yyyy"];
NSString *dateStr = [dateFormatter stringFromDate:date];
myDate.text = dateStr;
例如,如果日期 = 2 月 12 日; myDate .text = @"母亲节";
类似的东西
【问题讨论】:
【参考方案1】:确实如此。您必须使用 NSDateComponents 将日期拆分为日和月
你可以这样写一个方法:
- (BOOL)date:(NSDate *)date isSameAsDay:(NSInteger)day andMonth:(NSInteger)month
NSUInteger dateFlags = NSDayCalendarUnit | NSMonthCalendarUnit;
NSDateComponents *components = [[NSCalendar currentCalendar] components:dateFlags fromDate:date];
if ([components day] == day && [components month] == month)
return YES;
return NO;
你会这样使用它
if ([self date:[NSDate date] isSameAsDay:12 andMonth:2])
myDate.text = @"Mother Day";
【讨论】:
【参考方案2】:应该这样做:
NSDate *today = [NSDate date]; // Get ref to todays date
NSCalendar *gregorian = [[NSCalendar alloc]
initWithCalendarIdentifier:NSGregorianCalendar];
NSDateComponents *weekdayComponents =
[gregorian components:(NSWeekdayOrdinalCalendarUnit | NSWeekdayCalendarUnit | NSMonthCalendarUnit) fromDate:today];
NSInteger weekday = [weekdayComponents weekday]; // Sun == 1, Mon == 2, Tue...
NSInteger weekdayOrdinal = [weekdayComponents weekdayOrdinal]; // First weekday month == 1 etc...
NSInteger month = [weekdayComponents month];
NSLog (@"%i %i %i", weekday, weekdayOrdinal, month);
// Mothers day is every second Sunday of May so weekday == 1, weekdayOrdinal == 2, month == 5
if ((weekday == 1) && (weekdayOrdinal == 2) && (month == 5))
NSLog (@"It's mothers day!");
[gregorian release];
【讨论】:
以上是关于使用 NSDate 创建事件的主要内容,如果未能解决你的问题,请参考以下文章