gpt4 book ai didi

ios - 从 Objective-C 中的字符串获取日期

转载 作者:可可西里 更新时间:2023-11-01 05:03:56 26 4
gpt4 key购买 nike

我必须从字符串中获取日期,此处字符串的格式为“Monday 02,Dec 2013”​​,我必须将其转换为“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);
}

最佳答案

试试这个,它适用于 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 ;-)

关于ios - 从 Objective-C 中的字符串获取日期,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20245484/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com