从目标C中的字符串获取日期

时间:2013-11-27 14:46:45

标签: ios objective-c nsdate nsdateformatter

我必须从字符串中获取日期,此处的字符串格式为“2013年12月2日星期一”我必须将其转换为“2013-12-2”。我使用了以下代码,但我得到了输出错误:

-(void)dateSelectedInPickerView:(NSString *)dateSelected{

    NSDateFormatter *dateFormatterForGettingDate = [[NSDateFormatter alloc] init];
    [dateFormatterForGettingDate setDateFormat:@"YYYY-MM-dd HH:mm:ss"];

    // Parse the string representation of the date i.e Monday 2,Dec 2013

    NSDate *dateFromStr = [dateFormatter dateFromString:dateSelected];
    NSLog(@"date selected  : %@",dateFromStr);

    NSDateFormatter *tempFormatter=[[NSDateFormatter alloc]init];
    [tempFormatter setDateFormat:@"YYYY-MM-dd"];

    self.reservationDateSelected=[tempFormatter stringFromDate:dateFromStr];
    NSLog(@"date Selected : %@",self.reservationDateSelected);
}

2 个答案:

答案 0 :(得分:7)

试试这个,它适用于Monday 02,Dec 2013

-(void)dateSelectedInPickerView:(NSString *)dateSelected{

NSDateFormatter *dateFormatterForGettingDate = [[NSDateFormatter alloc] init];
[dateFormatterForGettingDate setDateFormat:@"EEEE dd,MMM yyyy"];
[dateFormatterForGettingDate setLocale:[NSLocale localeWithLocaleIdentifier:@"EN"]];

// Parse the string representation of the date i.e Monday 2,Dec 2013

NSDate *dateFromStr = [dateFormatterForGettingDate dateFromString:dateSelected];
NSLog(@"date selected  : %@", [dateFromStr descriptionWithLocale:[NSLocale currentLocale]]);
NSDateFormatter *tempFormatter=[[NSDateFormatter alloc]init];
[tempFormatter setDateFormat:@"yyyy-MM-dd"];

self.reservationDateSelected=[tempFormatter stringFromDate:dateFromStr];
NSLog(@"date Selected : %@",self.reservationDateSelected);

}

Read this, if want to know more about Date Format Patterns ;-)

答案 1 :(得分:5)

1)您应该使用yyyy,而不是YYYYYYYY代表基于“年度周”的日历中的年份 - 它可能并不总是与日历年相同的值。请参阅documentation

2)解析“2013年12月2日星期一”的格式应为“EEEE dd,MMM yyyy”

EDIT 3)忘记关于语言环境 - 如果您不明确设置日期格式化程序的语言环境,那么具有非英语语言环境的设备将无法解析“2013年12月2日星期一”(因为“星期一”和“12月”) / p>

NSDateFormatter *dateFormatterForGettingDate = [[NSDateFormatter alloc] init];
dateFormatterForGettingDate.locale = [[NSLocale alloc] initWithLocaleIdentifier:@"en_US"];
[dateFormatterForGettingDate setDateFormat:@"EEEE dd,MMM yyyy"];

我认为,这应该有效:

-(void)dateSelectedInPickerView:(NSString *)dateSelected{

    NSDateFormatter *dateFormatterForGettingDate = [[NSDateFormatter alloc] init];
    dateFormatterForGettingDate.locale = [[NSLocale alloc] initWithLocaleIdentifier:@"en_US"];
    [dateFormatterForGettingDate setDateFormat:@"EEEE dd,MMM yyyy"];

    // Parse the string representation of the date i.e Monday 2,Dec 2013

    NSDate *dateFromStr = [dateFormatter dateFromString:dateSelected];
    NSLog(@"date selected  : %@",dateFromStr);

    NSDateFormatter *tempFormatter=[[NSDateFormatter alloc]init];
    [tempFormatter setDateFormat:@"yyyy-MM-dd"];

    self.reservationDateSelected=[tempFormatter stringFromDate:dateFromStr];
    NSLog(@"date Selected : %@",self.reservationDateSelected);
}