Problem while converting nsstring to nsdate and viceversa
I am facin开发者_高级运维g a problem while converting from date to string and string to date.
code is :
NSDate *date=[NSDate date];
NSDateFormatter *formatter=[[NSDateFormatter alloc] init];
[formatter setDateFormat:@"dd/MM/YYYY"];
NSString *dateString=[formatter stringFromDate:date];
NSDateFormatter *dateFormat = [[NSDateFormatter alloc] init];
[dateFormat setDateFormat:@"dd/MM/YYYY"];
NSDate *date2 = [dateFormat dateFromString:dateString];
while printing it is displaying the different date. Kindly help me
NSDate always returns in GMT. So date2
is right. Its in GMT. You can consider it as 27/05/2011 00:00:00 +0530 IST
. There is nothing wrong with this.
NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
[dateFormatter setDateFormat:@"dd/MM/YYYY"];
[dateFormatter setTimeZone:[NSTimeZone timeZoneWithName:@"IST"]];
NSLog(@"%@", [dateFormat stringFromDate:date2]);
Doing this should return in IST.
You can also get date2
like this,
NSCalendar *gregorian = [[NSCalendar alloc] initWithCalendarIdentifier:NSGregorianCalendar];
NSInteger flag = NSYearCalendarUnit | NSMonthCalendarUnit | NSDayCalendarUnit;
NSDateComponents *dateComponents = [gregorian components:flag fromDate:[NSDate date]];
NSDate *date2 = [gregorian dateFromComponents:dateComponents];
精彩评论