0

我试图从 11 月 3 日开始添加像达拉斯这样的时区的一天,但我做不到。

NSDate *intime = @"2013-11-03 05:00:00 +0000";

NSDate *nextday= [NSDate dateWithTimeInterval:24*3600 sinceDate:intime];

NSDateFormatter *formatter=[[NSDateFormatter alloc]init];
[formatter setDateFormat:@"MM/dd/yyyy"];
NSString *convert=[formatter stringFromDate:nextday];
NSLog(@"convert:%@",convert);

nslog 值:

intime:  2013-11-03 05:00:00 +0000
nextday: 2013-11-04 05:00:00 +0000
convert: 11/03/2013 23:00:00 // but I need this 11/04/2013.

请告诉我,如何做到这一点,

提前致谢

4

1 回答 1

1

问题在于intime- 您必须使用格式化程序来初始化NSDate来自字符串。所以我测试的例子是:

//  NSDate *intime = @"2013-11-03 05:00:00 +0000"; // wrong

NSString *str =@"2013-11-03 05:00:00 +0000";
NSDateFormatter *formatter = [[NSDateFormatter alloc]init];
[formatter setDateFormat:@"yyyy-MM-dd HH:mm:ss ZZZ"];
NSDate *intime = [formatter dateFromString:str];

NSDate *nextday= [NSDate dateWithTimeInterval:24*3600 sinceDate:intime];

NSDateFormatter *formatter2=[[NSDateFormatter alloc]init];
[formatter2 setDateFormat:@"MM/dd/yyyy"];
NSString *convert=[formatter2 stringFromDate:nextday];
NSLog(@"%@, %@, %@", intime, nextday, convert);

输出是:

2013-08-08 15:03:23.762 2013-11-03 05:00:00 +0000, 2013-11-04 05:00:00 +0000, 11/04/2013

一个小评论:默认情况下,当打开显示问题时,XCode 会用代码写出这类问题(首选项->常规->显示实时问题)。例如。在这种情况下,XCode 会警告您这个问题:Incompatible pointer types initializing 'NSDate *__strong' with an expression of type 'NSString *'

于 2013-08-08T13:04:18.997 回答