2011-04-07 101 views
8

初学者的问题的日子,但我想知道如果有人能帮助我:的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 

因此,这会给我一定的格式的日期。但是,我想知道如何访问此日期的某些部分。有 - (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 

回答

25

n.evermind,

你会需要这样的事:

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); 

输出

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 

欢呼声中,乔丹

+0

非常感谢。这真的很有帮助,非常感谢。 – 2011-04-07 18:45:16

+0

只是另一件事:我怎么才能得到今天的日期?即在你的例子中它是静态日期= [格式化程度dateFromString:@“2011年4月7日”];谢谢你的帮助! – 2011-04-07 19:01:24

+0

NSDate date = [NSDate date];会给你今天的日期。在这种情况下,您不需要上述代码中的第一个NSDateFormatter。 – Jordan 2011-04-07 19:16:26

0

你应该采取NSDateFormatter

+0

谢谢,但文档是相当很难去。我想我需要 - (NSArray *)weekdaySymbols,但不知道如何在我的上下文中使用它。 – 2011-04-07 16:15:13

0

一看那@ n.evermind

你应该看看NSCalendar,特别是- components:fromDate方法,该方法可以为您提供所需的所有物料的NSDateComponents对象。

相关问题