2011-04-07 102 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對象。

相關問題