初学者的问题,但我想知道是否有人可以帮助我解决这个问题:
我需要根据包含特定日期的字符串设置四个字符串(例如@“Apr 7, 2011”):
- 表示星期几的字符串(缩写:Mon、Tue、Wed、Thu、Fri、Sat、Sun):例如
@"Thu"
- 需要一天的字符串,例如
@"7"
- 表示月份的字符串,例如
@"April"
- 和一个表示年份的字符串,例如
@"2011"
到目前为止,我发现了这个:
NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
[dateFormatter setTimeStyle:NSDateFormatterNoStyle];
[dateFormatter setDateStyle:NSDateFormatterMediumStyle];
NSDate *date = [NSDate dateWithTimeIntervalSinceReferenceDate:118800];
NSLocale *usLocale = [[NSLocale alloc] initWithLocaleIdentifier:@"en_US"];
[dateFormatter setLocale:usLocale];
NSLog(@"Date for locale %@: %@",
[[dateFormatter locale] localeIdentifier], [dateFormatter stringFromDate:date]);
// Output:
// Date for locale en_US: Jan 2, 2001
所以这会给我一个特定格式的日期。然而,我想知道如何访问该日期的某些部分。有 - (NSArray *)weekdaySymbols 但我不知道如何使用这个,而且文档非常节俭。
日历专家的任何提示都将非常受欢迎。
EDIT:
我想这是解决方案的一部分:
NSLocale *gbLocale = [[NSLocale alloc] initWithLocaleIdentifier:@"en_GB"];
NSString *gbFormatString = [NSDateFormatter dateFormatFromTemplate:@"EdMMM" options:0 locale:gbLocale];
NSLog(@"gbFormatterString: %@", gbFormatString);
// Output: gbFormatterString: EEE d MMM, e.g. Thu 7 Apr
没关系,
你将需要这样的东西:
NSDate *date = [NSDate date];
NSDateFormatter *formatter = [[[NSDateFormatter alloc] init] autorelease];
[formatter setDateFormat:@"MMM dd, yyy"];
date = [formatter dateFromString:@"Apr 7, 2011"];
NSLog(@"%@", [formatter stringFromDate:date]);
NSCalendar *calendar = [NSCalendar currentCalendar];
NSInteger units = NSYearCalendarUnit | NSMonthCalendarUnit | NSDayCalendarUnit | NSWeekdayCalendarUnit;
NSDateComponents *components = [calendar components:units fromDate:date];
NSInteger year = [components year];
NSInteger month=[components month]; // if necessary
NSInteger day = [components day];
NSInteger weekday = [components weekday]; // if necessary
NSDateFormatter *weekDay = [[[NSDateFormatter alloc] init] autorelease];
[weekDay setDateFormat:@"EEE"];
NSDateFormatter *calMonth = [[[NSDateFormatter alloc] init] autorelease];
[calMonth setDateFormat:@"MMMM"];
NSLog(@"%@ %i %@ %i", [weekDay stringFromDate:date], day, [calMonth stringFromDate:date], year );
output
2011-04-07 12:49:23.519 test[7296:207] Apr 07, 2011
2011-04-07 12:49:23.521 test[7296:207] Thu 7 April 2011
干杯,乔丹
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)