NSDate object reciving fron NSString with different values

旧城冷巷雨未停 提交于 2019-12-13 09:25:18

问题


i like to fetch local device time and assign to string object .

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

output received = 6 March , 2013

convert NSString to NSDate object back code below

NSDateFormatter *uu=[[NSDateFormatter alloc]init];
[uu setDateFormat:@"d MMMM , yyyy"];

NSDate *yy=[uu dateFromString:self.dateSting];

output recived=2013-03-05 18:30:00 +0000 difference coming in days.


回答1:


Try something like this.

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

The difference in date and time occurs due to the GMT offset. NSLogging NSDate give you time with the offset. The offset shows the value to be added or subtracted from date. In India its +5.30. Always make sure to keep the offset details as they may change the actual date if absent. Hope this helps.




回答2:


Well, the solution is fairly simple. NSDate always shows GMT. And from you profile, I can see that your present location is INDIA , where the local time zone is GMT +5.30hrs.

The current output you got is 2013-03-05 18:30:00 +0000 to which if you add 5.30hrs you will get 2013-03-06 00:00:00 +0000. Please note that at the end of NSDate you can see something like +0000, this shows the timezone.

This is the reason/solution for your question and if you want to know how get it solved ,the answer is here.

Hope everything is clear now.




回答3:


dateWithString: Creates and returns an NSDate object with a date and time value specified by a given string in the international string representation format (YYYY-MM-DD HH:MM:SS ±HHMM).

  • (id)dateWithString:(NSString *)aString Parameters aString A string that specifies a date and time value in the international string representation format—YYYY-MM-DD HH:MM:SS ±HHMM, where ±HHMM is a time zone offset in hours and minutes from GMT (for example, “2001-03-24 10:45:32 +0600”). You must specify all fields of the format string, including the time zone offset, which must have a plus or minus sign prefix.


来源:https://stackoverflow.com/questions/15240170/nsdate-object-reciving-fron-nsstring-with-different-values

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!