我想将输入字符串转换为特定的NSDate
格式,
这是我尝试过的代码。
NSString * result;
NSDate * resultDate;
NSDate *date = [dateFormat dateFromString:maxUpcomingDateString];
NSDateFormatter *dateFormat1 = [[NSDateFormatter alloc] init];
dateFormat1.locale=[[NSLocale alloc] initWithLocaleIdentifier:@"en_US"];
[dateFormat1 setDateFormat:@"yyyy/MMM/dd"];
NSLog(@"maxUpcomingDateString %@",maxUpcomingDateString)
NSDate *d=[dateFormat1 dateFromString:maxUpcomingDateString];
result = [dateFormat1 stringFromDate:date];
resultDate=[dateFormat1 dateFromString:result];
NSLog(@"max1 date upcoming %@",result);
NSLog(@"max2 date upcoming %@", resultDate);
我的日志输出显示:
maxUpcomingDateString 10 January 2017
max1 date upcoming 2017/Jan/10
max2 date upcoming (null)
我希望输出日期采用2017/Jan/10
的形式。当我尝试记录字符串时,它会向我显示正确的输出,但当我将其转换回NSDate
时,它显示为null。
答案 0 :(得分:0)
nsstring to nsdate
NSString *dateString = @"01-02-2010";
NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
// this is imporant - we set our input date format to match our input string
// if format doesn't match you'll get nil from your string, so be careful
[dateFormatter setDateFormat:@"dd-MM-yyyy"];
NSDate *dateFromString = [[NSDate alloc] init];
dateFromString = [dateFormatter dateFromString:dateString];
nsdate to nsstring
NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
[dateFormatter setDateFormat:@"dd-MM-yyyy"];
NSString *stringDate = [dateFormatter stringFromDate:[NSDate date]];
NSLog(@"%@", stringDate);
答案 1 :(得分:-1)
在dateFormat
上添加此代码[dateFormat setDateFormat:@"dd MMM yyyy"];
它将解决问题。
答案 2 :(得分:-1)
在分配dateFormat对象后添加此代码。
NSDateFormatter *dateFormat = [[NSDateFormatter alloc] init];
[dateFormat setDateFormat:@"dd MMM yyyy"];