objective-c:将日期字符串转换为星期几+月份名称

n.e*_*ind 8 iphone datetime cocoa-touch objective-c

一个初学者的问题,但我想知道是否有人可以帮我这个:

我需要根据包含特定日期的字符串设置四个字符串(例如@"2011年4月7日"):

  • 一个字符串,它将采用星期几(缩写:周一,周二,周三,周四,周五,周六,周日):例如 @"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
Run Code Online (Sandbox Code Playgroud)

所以这会给我一个特定的格式化日期.然而,我想知道如何访问这个日期的某些部分.有 - (NSArray*)weekdaySymbols但我不知道如何使用这个,文档非常节俭.

日历专家提供的任何提示都将非常受欢迎.


编辑:

我想这是解决方案的一部分:

    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
Run Code Online (Sandbox Code Playgroud)

Jor*_*dan 25

没关系,

你需要这样的东西:

    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 );
Run Code Online (Sandbox Code Playgroud)

产量

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
Run Code Online (Sandbox Code Playgroud)

干杯,乔丹