在将NSString转换为NSDate时?

时间:2016-05-06 07:13:28

标签: ios objective-c nsstring nsdate

我尝试使用以下代码将NSString转换为NSDate

NSString *dateString=[[NSString alloc] init];
dateString = [[messageArray objectAtIndex:i] tim_dte];
NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
[dateFormatter setDateFormat:@"HH:mm,yyyy/MM/dd"];
NSDate *dateFromString = [[NSDate alloc] init];
dateFromString = [dateFormatter dateFromString:dateString];
msg.date = dateFromString;

但即使msg.Date显示正确的日期字符串,nil仍为dateString。我错过了什么?

3 个答案:

答案 0 :(得分:1)

更改此格式

[dateFormatter setDateFormat:@"HH:mm,yyyy/MM/dd"];

进入并尝试

[dateFormatter setDateFormat:@"yyyy/MM/dd HH:mm"];

<强>更新

NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
[dateFormatter setDateFormat:@"yyyy/MM/dd HH:mm"];
// use simple 
msg.date =   [dateFormatter dateFromString:@"2016/05/06 12:36"];
  NSLog(@"final date == %@",dateFromString);
//NSDate *dateFromString = [dateFormatter dateFromString:@"2016/05/06 12:36"];

// NSLog(@"final date == %@",dateFromString);

答案 1 :(得分:0)

使用此代码,

NSString *dateString=[[NSString alloc] init];
dateString =[[messageArray objectAtIndex:i] tim_dte];
NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
[dateFormatter setDateFormat:@"yyyy/MM/dd HH:mm"];
NSDate *dateFromString = [[NSDate alloc] init];
dateFromString = [dateFormatter dateFromString:dateString];
msg.date=dateFromString;

希望它有用

答案 2 :(得分:0)

尝试使用此代码将NSString转换为NSDate

NSString *dateString = @"2016-05-06";
NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
[dateFormatter setDateFormat:@"yyyy-MM-dd'T'HH:mm:ssZ"];
NSDate *date = [dateFormatter dateFromString:@"2013-02-01T06:25:47Z"];
NSTimeZone *pdt = [NSTimeZone timeZoneWithAbbreviation:@"PDT"];
[dateFormatter setTimeZone:pdt];
[dateFormatter setDateFormat:@"HH:mm:ss zzz"];
[dateFormatter setDateFormat:@"K:mm a, z"];
NSString * updated String = [dateFormatter stringFromDate:date];