我一直在努力将nsstring转换为nsdate格式。我有一个nsstring格式的日期,如(2011-08-25 18:30:00 +0000),但我想以nsdate格式(08/26/2011)更改它。怎么改呢?有人能帮帮我吗?在此先感谢...我花了一天时间来解决这个问题,但我找不到解决方案..请帮助我的朋友....
这是我的代码,
NSString *dateString = @"2011-08-25 18:30:00 +0000";
NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
[dateFormatter setDateFormat:@"MM/dd/yyyy"];
NSDate *dateFromString = [[NSDate alloc] init];
dateFromString = [dateFormatter dateFromString:dateString];
NSLog(@"Converted date is %@",dateFromString);
输出是,
Converted date is (null)
Yuva.M
答案 0 :(得分:10)
NSString *dateWithInitialFormat = @"2011-08-25 18:30:00 +0000";
NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
[dateFormatter setDateFormat:@"yyyy-MM-dd HH:mm:ss Z"];
NSDate *date = [dateFormatter dateFromString:dateWithInitialFormat];
[dateFormatter setDateFormat:@"MM/dd/yyyy"];
NSString *dateWithNewFormat = [dateFormatter stringFromDate:date];
NSLog(@"dateWithNewFormat: %@", dateWithNewFormat);
来自NSLog:dateWithNewFormat:08/25/2011
答案 1 :(得分:1)
您需要使用NSDateFormatter并设置日期格式以匹配您的存储方式,如下所示。
NSDateFormatter *df = [[NSDateFormatter alloc] init];
[df setDateFormat:@"yyyy-MM-dd hh:mm:ss"];
NSDate *myDate = [df dateFromString: myDateString];
答案 2 :(得分:0)
NSDateFormatter* df = [[NSDateFormatter alloc] init];
[df setDateFormat:@"MMMM dd, yyyy"];
NSDate* d = [df dateFromString:@"January 06, 1992"];
NSLog(@"%@", d);
NSDate *dispalyDate = d;
NSDateFormatter *dateFormat = [[NSDateFormatter alloc] init];
[dateFormat setDateFormat:@"dd MMM"];
NSString *str = [dateFormat stringFromDate:dispalyDate];
NSLog(@"%@", str);