2011-07-18 50 views
1

我知道这是一个重复性的查询,但我很困扰这个问题。 我需要知道如何才能获得星期一,星期二的特定日期,例如:2010年7月18日等。如何查找使用Cocoa的任何给定日期的星期几?

感谢您的帮助!

+0

也许这有助于http://stackoverflow.com/问题/ 3694867/NSDate的,得到年 - 月 - 日? – Mat

+0

您是否想要打印出“Mon”,如果是这种情况,您需要利用NSDateFormatter –

+0

@Greg:我刚写了缩写,但应该是星期一,星期二等。 – Manoj

回答

0
NSString *dateString = @"20 July, 2011"; // select this from your database 

NSDateFormatter *dateFormatter = [[[NSDateFormatter alloc] init] autorelease]; 
[dateFormatter setDateFormat:@"dd MMMM, yyyy"]; 
NSDate *date = [dateFormatter dateFromString:dateString]; 

NSCalendar *gregorian = [[NSCalendar alloc] initWithCalendarIdentifier:NSGregorianCalendar]; 
NSDateComponents *components = [gregorian components:NSWeekdayCalendarUnit fromDate:date]; 
NSInteger weekday = [components weekday]; 
NSLog(@"%d", weekday); 

注意,周日为1
2是星期一等等

编辑我的答案告诉你如何将字符串转换的例子到NSDate。 ;)

+0

pawan.mangal的解决方案会将星期几作为字符串返回,甚至可能是本地化的。但是,如果您想将其存储在数据库或类似的数据库中,则整数可能更有用。 –

+0

您每次查看当前日期,可以说我从我的列表中选择2007年12月11日,我想知道当天的数字是多少。希望我对你很清楚。 – Manoj

+0

那么,你必须将该字符串(?)转换为NSDate并使用它来代替[NSDate date]; ;) –

0

试试这个

NSDateFormatter* theDateFormatter = [[[NSDateFormatter alloc] init] autorelease]; 
    [theDateFormatter setFormatterBehavior:NSDateFormatterBehavior10_4]; 
    [theDateFormatter setDateFormat:@"EEEE"]; 
    NSString *weekDay = [theDateFormatter stringFromDate:[NSDate date]]; 
+0

请检查我的意见,以Jenox的答案。 – Manoj

1

要打印出当天的文字表述和NSDate的,请尝试以下操作:

NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init]; 
[dateFormatter setDateFormat:@"EEEE"]; 
[dateFormatter release]; 

NSDate *myDate = [NSDate date]; 

NSString *day = [dateFormatter stringFromDate:myDate]; 

欲了解更多有关http://unicode.org/reports/tr35/tr35-10.html#Date_Format_Patterns

+0

感谢Greg的回答。 – Manoj

相关问题