Iphone 从具有不同值的NSString接收的NSDate对象

Iphone 从具有不同值的NSString接收的NSDate对象,iphone,ios,nsdate,Iphone,Ios,Nsdate,我喜欢获取本地设备时间并分配给string对象 NSDate* currentDate = [NSDate date]; NSDateFormatter *dateformatter=[[NSDateFormatter alloc]init]; [dateformatter setDateFormat:@"d MMMM , yyyy"]; self.dateSting=[[NSMutableString alloc]init]; self.dateSting = [NSMutableString

我喜欢获取本地设备时间并分配给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];
接收到的输出=2013-03-05 18:30:00+0000
几天后就会有不同。

好吧,解决方案相当简单<代码>NSDate始终显示。 从你的个人资料中,我可以看到你现在的位置是,当地时区是GMT+5.30小时

您获得的当前输出是
2013-03-05 18:30:00+0000
,如果您在其中添加5.30小时,您将获得
2013-03-06 00:00+0000
。请注意,在
NSDate
的末尾,您可以看到类似
+0000
的内容,这显示了时区

这就是你问题的原因/解决方案,如果你想知道如何解决它,请点击

希望现在一切都清楚了。

日期字符串: 创建并返回NSDate对象,其日期和时间值由给定字符串以国际字符串表示格式(YYYY-MM-DD HH:MM:SS±HHMM)指定

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

    • 试试这样的方法

      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]);
      

      日期和时间的差异是由GMT偏移引起的。NSLogging NSDate为您提供时间和偏移量。偏移量显示要从日期中添加或减去的值。印度为+5.30。始终确保保留偏移详细信息,因为如果缺少,它们可能会更改实际日期。希望这能有所帮助。

      始终保持日期的常规格式以及时间及其偏移量,当您需要按格式显示日期时,请使用格式化程序,将其格式化为所需格式,然后显示。如果对偏移量进行了剪裁,则可能会由于时间区域的差异而导致时间和日期不准确设置外观[dateFormatter setDateFormat:@“d MMMM hh:mm:ss,yyyy”];NSDateFormatter*DateFormatter 1=[[NSDateFormatter alloc]init];[dateFormatter1 setDateFormat:@“hh:mm a”];NSString*formattedDateString=[dateFormatter1 stringFromDate:date];NSLog(@“yyy=%@”,formattedDateString);它给出的答案是Am,但应该是PMIt,它显示了正确的值。当我使用这个代码时,我得到了正确的值。请查收。我得到的PM与当前时间有关。第二个日志记录到NSDate,第一个记录在NSString上,NSDate将始终以GMT 00:00显示。你应该通过@MicRO接受答案