簡體   English   中英

objective-c:將日期字符串轉換為星期幾+月份名稱

[英]objective-c: converting date string into day of the week + month name

一個初學者的問題,但我想知道是否有人可以幫我這個:

我需要根據包含特定日期的字符串設置四個字符串(例如@“2011年4月7日”):

  • 一個星期幾的字符串(縮寫: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但我不知道如何使用這個,文檔非常節儉。

日歷專家提供的任何提示都將非常受歡迎。


編輯:

我想這是解決方案的一部分:

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

產量

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

干杯,喬丹

你應該看看NSDateFormatter

@沒關系

實際上你應該看看NSCalendar ,特別是- components:fromDate方法,它為你提供了NSDateComponents對象,它擁有你想要的所有peices。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM