您不能使用相同的格式化程序来读取和写入日期字符串,因为它们是不同的。您输入日期的格式不正确。
// input string date: 2015-04-18 06:08:28.000000
// [formatter setDateFormat:@"d/M/yyyy"]; // incorrect
[formatter setDateFormat:@"yyyy-MM-dd HH:mm:ss.SSSSSS"];
下面是示例代码
//
// main.m
// so29732496
//
// Created on 4/19/15.
//
#import <Foundation/Foundation.h>
int main(int argc, const char * argv[]) {
@autoreleasepool {
NSLog(@"Hello, World!");
NSString *dateStringFromAPI = @"2015-04-18 06:08:28.000000";
NSString * const kAPIDateFormat = @"yyyy-MM-dd HH:mm:ss.SSSSSS";
// convert API date string
NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
[formatter setDateFormat:kAPIDateFormat];
NSDate *apiDate = [formatter dateFromString:dateStringFromAPI];
// now if I was output the api date to another format
// I have to change the formatter
[formatter setDateFormat:@"dd/M/yyyy"];
NSString *currentDate = [formatter stringFromDate:apiDate];
NSLog(@"Current Date: %@", currentDate);
}
return 0;
}