使用 NSDateFormatter 将字符串转换为日期
Converting string to date with NSDateFormatter
我正在尝试将此字符串 '2015-05-08T09:44:25.343' 格式转换为日期 'dd/MM/YYYY' 格式
我做错了什么?我的约会对象是零。
// convert 2015-05-08T09:44:25.343 to dd/MM/yyyy
NSString *str = @"2015-05-08T09:44:25.343";
NSDateFormatter *dateFormat = [[NSDateFormatter alloc]init];
[dateFormat setDateFormat:@"dd/MM/yyyy"];
NSDate *date = [dateFormat dateFromString:str];
NSLog(@"%@",date);
NSString *convertedString = [dateFormat stringFromDate:date];
NSLog(@"%@", convertedString);
您的格式字符串与您提供的日期格式不匹配。试试这个。
NSString *str = @"2015-05-08T09:44:25.343";
NSDateFormatter *dateFormat = [[NSDateFormatter alloc]init];
[dateFormat setDateFormat:@"yyyy-MM-dd'T'HH:mm:ss.SSS"];
NSDate *date = [dateFormat dateFromString:str];
然后您可以根据需要进行转换。
NSString *str = @"2015-05-08T09:44:25.343";
NSDateFormatter *dateFormat = [[NSDateFormatter alloc]init];
[dateFormat setDateFormat:@"yyyy'-'MM'-'dd'T'HH':'mm':'ss.SSS'Z'"];// this string must match given string @"2015-05-08T09:44:25.343"
NSDate *date = [dateFormat dateFromString:str];
NSLog(@"%@",date);
[dateFormat setDateFormat:@"MM/dd/yyyy"];// this match the one you want to be
NSString *convertedString = [dateFormat stringFromDate:date];
NSLog(@"%@", convertedString);
我正在尝试将此字符串 '2015-05-08T09:44:25.343' 格式转换为日期 'dd/MM/YYYY' 格式
我做错了什么?我的约会对象是零。
// convert 2015-05-08T09:44:25.343 to dd/MM/yyyy
NSString *str = @"2015-05-08T09:44:25.343";
NSDateFormatter *dateFormat = [[NSDateFormatter alloc]init];
[dateFormat setDateFormat:@"dd/MM/yyyy"];
NSDate *date = [dateFormat dateFromString:str];
NSLog(@"%@",date);
NSString *convertedString = [dateFormat stringFromDate:date];
NSLog(@"%@", convertedString);
您的格式字符串与您提供的日期格式不匹配。试试这个。
NSString *str = @"2015-05-08T09:44:25.343";
NSDateFormatter *dateFormat = [[NSDateFormatter alloc]init];
[dateFormat setDateFormat:@"yyyy-MM-dd'T'HH:mm:ss.SSS"];
NSDate *date = [dateFormat dateFromString:str];
然后您可以根据需要进行转换。
NSString *str = @"2015-05-08T09:44:25.343";
NSDateFormatter *dateFormat = [[NSDateFormatter alloc]init];
[dateFormat setDateFormat:@"yyyy'-'MM'-'dd'T'HH':'mm':'ss.SSS'Z'"];// this string must match given string @"2015-05-08T09:44:25.343"
NSDate *date = [dateFormat dateFromString:str];
NSLog(@"%@",date);
[dateFormat setDateFormat:@"MM/dd/yyyy"];// this match the one you want to be
NSString *convertedString = [dateFormat stringFromDate:date];
NSLog(@"%@", convertedString);