將下面的日期字符串轉換成其他格式。操作如下:
NSLog(@"datestring is NOW %@",_dayObject.p_date);
NSDateFormatter *dateFormat = [[NSDateFormatter alloc] init];
[dateFormat setDateFormat:@"YYYY-MM-DD"];
NSDate *date = [dateFormat dateFromString:_dayObject.p_date];
NSLog(@"date transformed %@",date);
[dateFormat setDateFormat:@"EEEE, dd/MM/YYYY"];
[dateFormat setTimeZone:[NSTimeZone timeZoneWithAbbreviation:@"GMT"]];
NSString *dateStr = [dateFormat stringFromDate:date];
NSLog(@"datestring is AFTER %@",dateStr);
但是在NSLog中得到:
2013-04-18 08:43:36.181 mosaqua2[9629:907] datestring is NOW 2013-05-04
2013-04-18 08:43:36.184 mosaqua2[9629:907] date transformed 2013-01-03 23:00:00 +0000
2013-04-18 08:43:36.184 mosaqua2[9629:907] datestring is AFTER donderdag, 03/01/2013
正確的格式是: Saterday, 04/05/2013
謝謝您的解答。
NSLog(@"datestring is NOW %@",_dayObject.p_date);
NSDateFormatter *dateFormat = [[NSDateFormatter alloc] init];
NSTimeZone *GTMzone = [NSTimeZone timeZoneForSecondsFromGMT:0];
[dateFormat setDateFormat:@"YYYY-MM-dd"];
[dateFormat setTimeZone:GTMzone];
NSDate *date = [dateFormat dateFromString:_dayObject.p_date];
NSLog(@"date transformed %@",date);
[dateFormat setDateFormat:@"EEEE, dd/MM/YYYY"];
[dateFormat setTimeZone:[NSTimeZone timeZoneWithAbbreviation:@"GMT"]];
NSString *dateStr = [dateFormat stringFromDate:date];
NSLog(@"datestring is AFTER %@",dateStr);
使用NSDateFormatter轉換時間字符串時,默認的時區是系統時區,我們使用的一般都是北京時間(+8)