NSDate对象使用不同的值来调用NSString

我喜欢获取本地设备的时间和分配给string对象。

NSDate* currentDate = [NSDate date]; NSDateFormatter *dateformatter=[[NSDateFormatter alloc]init]; [dateformatter setDateFormat:@"d MMMM , yyyy"]; self.dateSting=[[NSMutableString alloc]init]; self.dateSting = [NSMutableString stringWithFormat:@"%@" ,[dateformatter stringFromDate:currentDate]]; 

收到的产出= 2013年3月6日

NSString转换为NSDate对象后面的代码

 NSDateFormatter *uu=[[NSDateFormatter alloc]init]; [uu setDateFormat:@"d MMMM , yyyy"]; NSDate *yy=[uu dateFromString:self.dateSting]; 

输出recived = 2013-03-05 18:30:00 +0000天来。

尝试这样的事情。

 NSDate* currentDate = [NSDate date]; NSLog(@"%@",currentDate); NSDateFormatter *dateformatter=[[NSDateFormatter alloc]init]; [dateformatter setDateFormat:@"d MMMM hh:mm:ss, yyyy"]; NSLog(@"%@",[dateformatter stringFromDate:currentDate]); NSDate *yy=[dateformatter dateFromString:[dateformatter stringFromDate:currentDate]]; NSLog(@"%@",yy); NSDateFormatter *uu=[[NSDateFormatter alloc]init]; [uu setDateFormat:@"d MMMM , yyyy"]; NSLog(@"%@",[uu stringFromDate:yy]); 

date和时间的差异是由GMT时差造成的。 NSLogging的NSDate给你的时间与抵消。 偏移量显示要从date添加或减去的值。 在印度其+5.30。 始终确保保留偏移量的详细信息,因为如果不存在,他们可能会更改实际date。 希望这可以帮助。

那么,解决scheme是相当简单的。 NSDate总是显示GMT 。 从你的个人资料中,我可以看到你现在的位置是印度 ,当地时区是GMT + 5.30小时。

你目前输出的是2013-03-05 18:30:00 +0000 ,如果你添加了5.30小时,你会得到2013-03-06 00:00:00 +0000 。 请注意,在NSDate的结尾处,您可以看到类似+0000 ,这显示了时区。

这是你的问题的原因/解决scheme,如果你想知道如何解决它, 答案就在这里 。

希望一切都清楚了。

dateWithString:以国际string表示格式(YYYY-MM-DD HH:MM:SS±HHMM)创build并返回一个由给定string指定的date和时间值的NSDate对象。

  • (id)dateWithString:(NSString *)aString参数aString以国际string表示格式指定date和时间值的string-YYYY-MM-DD HH:MM:SS±HHMM,其中,±HHMM是时区偏移小时和分钟(例如,“2001-03-24 10:45:32 +0600”)。 您必须指定格式string的所有字段,包括时区偏移量,该偏移量必须带有加号或减号前缀。