繁体   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