dateFromString返回nil。无法将日期转换为所需的格式

时间:2018-01-30 12:12:23

标签: ios objective-c nsdate nsdateformatter

这是我输入的nsstring 30/01/18 3:25 PM

我想要这种格式的日期:30 / Jan / 18 3:25 PM。

这是我试过的:

NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
dateFormatter setDateFormat:@"dd/MM/yy HH:mm "];
NSDate *date = [[NSDate alloc] init];
date = [dateFormatter dateFromString:releaseDate];
[dateFormatter setDateFormat:@"dd/MMM/yy HH:mm "];
NSString *finalDate = [dateFormatter stringFromDate:date];

我也试过这个:

NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
    [dateFormatter setDateFormat:@"dd/MM/yy HH:mm z"];
    NSDate *date = [[NSDate alloc] init];
    date = [dateFormatter dateFromString:releaseDate];
    [dateFormatter setDateFormat:@"dd/MMM/yy HH:mm z"];
    NSString *finalDate = [dateFormatter stringFromDate:date];

我总是把日期定为零!我做错了什么?

另外:时间有12小时格式和24小时格式。我如何同时处理这两个?

2 个答案:

答案 0 :(得分:-1)

你在功能下方检查它,它的工作正常: -

-(void)DateChange
 {
    NSString *Input_Date =@"31/01/18 04:25 AM";

    NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
    [dateFormatter setDateFormat:@"dd/mm/yy hh:mm a"];

    NSDate * Format_date = [dateFormatter dateFromString:Input_Date];
    [dateFormatter setDateFormat:@"dd/MMM/yy hh:mm a"];
    NSString *Change_date = [dateFormatter stringFromDate:Format_date];
    NSLog(@"Final Change Date :-  %@",Change_date);
}



My Output is :- 
Final Change Date :- 31/Jan/18 04:25 AM

答案 1 :(得分:-2)

使用Swift编写的此函数更改日期格式。它的工作不是

@Stateless