Reputation: 2113
I am receiving JSON data from a web service where the dates are in string format and includes the timezone format as you can see below:
{
currencyName = EUR;
itemID = 101064027138011;
price = "6.95";
priceIncTAX = 1;
validFromDate = "2016-11-03T00:00:00";
validToDate = "2020-01-01T00:00:00";
}
When I try convert the string that contains timezone into NSDate the return value is always nil/null, if I manually send in a string without the timezone info i,e @"2016-11-03" then the conversion works fine BUT the resulting date includes timezone offset etc and does not adhere to my dateFormatter
I use the following code to show the challenge at hand
NSString *validTo = @"2016-11-03";
NSString *validFrom = @"2020-11-03T00:00:00";
NSDateFormatter *dateFormat = [[NSDateFormatter alloc] init];
[dateFormat setDateFormat:@"YYYY-MM-dd"];
NSDate *validToDate = [dateFormat dateFromString:validTo];
NSDate *validFromDate = [dateFormat dateFromString:validFrom];
if([NWTillHelper isDebug] == 1) {
NSLog(@"WebServices:fetchPriceList:validToDate: >>>> %@ <<<<", validToDate);
NSLog(@"WebServices:fetchPriceList:validFromDate: %@", validFromDate);
}
The debugs tell me that the string without tz info works fine (apart from not adhering to my dateFormatter) but the string with tz info does not.
How can I convert a string that contains tz info to NSDate and why is it not adhering to my dateFormatter when I send in a string without timezone information.
016-11-27 12:09:22.194 NWMobileTill[4275:235671] WebServices:fetchPriceList:validToDate: >>>> 2016-11-02 16:00:00 +0000 <<<<
2016-11-27 12:09:22.194 NWMobileTill[4275:235671] WebServices:fetchPriceList:validFromDate: (null)
Upvotes: 0
Views: 321
Reputation: 11127
Change your date formatter from this
[dateFormat setDateFormat:@"YYYY-MM-dd"];
To this
[dateFormat setDateFormat:@"yyyy-MM-dd'T'HH:mm:ss"];
As your format is different which you are getting from server and in your code you are using different date format
Edit
As @rmaddy mentioned in his comment you are not getting timezone in your date string which you are getting from your server and date formatter will convert you string to date as per the user's current time zone.
As a suggestion I would like to mention to you that your date string must contain timezone as well something like this
2016-11-27T10:39:57-05:30
This string contains IST timezone and with your date formatter which is
[dateFormat setDateFormat:@"yyyy-MM-dd'T'HH:mm:ssZZZZZ"];
You will get the date as per the timezone of your date string not as per user's locale.
Upvotes: 1