Create a date from a string - ios

I'm pretty comfortable with core data now (only been iOS Developer for 6 months) but I haven't come upon having to put a date in core data.
So here's the situation. I'm pulling data from a web service in JSON format. One of the elements that I have is a date element and I don't know the syntax for properly storing this in core data.
If that isn't clear here is an example:
Syntax for storing a string:
newDate.eventyType = NSLocalizedString([diction objectForKey:#"eventyType"], nil);
Syntax for storing a number:
newDate.id = [NSNumber numberWithInt:[NSLocalizedString([diction objectForKey:#"id"], nil) intValue]];
So I need to know the syntax for storing a date.

Try like this:-
If you are extracting and storing your date from json format into NSString Variable then try below to convert into NSDate:-
NSString *strDate2=#"19-01-2014";
NSDateFormatter *format=[[NSDateFormatter alloc]init];
[format setDateFormat:#"dd-MM-yyyy"];
NSDate *dt1=[format dateFromString:strDate1];

As already answered before me, to create an NSDate object from NSString one uses NSDateFormatter. The important thing to know about the date formatter is that it uses user’s locale (including calendar!) and time zone. But the dates you expect to receive are probably in one, fixed locale and in one time zone. This can cause date formatter to fail parsing the date string.
The solution to this is to set the locale and the time zone to the date formatter explicitly:
NSDateFormatter *rfc3339DateFormatter = [[[NSDateFormatter alloc] init];
NSLocale *enUSPOSIXLocale = [[[NSLocale alloc] initWithLocaleIdentifier:#"en_US_POSIX”];
rfc3339DateFormatter.locale = enUSPOSIXLocale;
rfc3339DateFormatter.dateFormat = #"yyyy'-'MM'-'dd”;
rfc3339DateFormatter.timeZone = [NSTimeZone timeZoneForSecondsFromGMT:0];
See Technical Q&A QA1480 for more detailed explanation.

Related

What is the proper way to convert date object with separate timezone into NSDate

My app ingests data from a web service (PHP) which provides dates in this format:
endDate = {
date = "2020-09-30 16:16:08.000000";
timezone = "-04:00";
"timezone_type" = 1;
};
This is the code I have been using to convert to NSDate, and it works as far as I can tell, in every test, but it fails on a few devices according to user reports and debug logs.
Note that the correct conversion of this date determines if content is unlocked in the app, so when it fails, customers contact us about it.
NSDictionary* dateDict = [responseDict objectForKey:#"endDate"];
NSString* strEndDate = [dateDict objectForKey:#"date"];
NSString* strOffset = [dateDict objectForKey:#"timezone"];
NSTimeInterval zoneSeconds = 0;
NSRange rng = [strOffset rangeOfString:#":"];
if (rng.location != NSNotFound && rng.location >= 1)
{
NSString* hoursOnly = [strOffset substringToIndex:rng.location];
NSInteger offsetValue = [hoursOnly integerValue];
zoneSeconds = (3600 * offsetValue);
}
NSDateFormatter* df = [[NSDateFormatter alloc] init];
NSTimeZone *timeZone = [NSTimeZone timeZoneForSecondsFromGMT:zoneSeconds];
[df setTimeZone:timeZone];
[df setDateFormat:#"yyyy-MM-dd HH:mm:ss.000000"];
NSDate* newEndDate = [df dateFromString:strEndDate];
However, debug logs from a few users show that the dateFromString call is failing and returning nil.
We have one user who has 2 iOS devices, and using the same account (same date) the app performs as expected on one of them, but fails on the other. Same Apple ID, both running iOS12. Debug logs show both devices received the same date from the server, yet one of them failed to convert the date from a string to NSDate.
My assumption so far is that there is some setting or configuration on the device(s) where this fails that is different. But I have fiddled with calendar and date settings all day, and cannot get this to fail. I know the user in question has both devices configured to the same time zone.
Is there a better, more correct way to do this date conversion which might be more robust?
When using an arbitrary date format it's highly recommended to set the locale of the date formatter to the fixed value en_US_POSIX.
Rather than calculating the seconds from GMT it might be more efficient to strip the milliseconds with regular expression, append the string time zone and use an appropriate date format.
This code uses more contemporary syntax to set date formatter properties with dot notation and dictionary literal key subscription
NSDictionary *dateDict = responseDict[#"endDate"];
NSString *strEndDate = dateDict[#"date"];
NSString *strTimeZone = dateDict[#"timezone"];
NSString *dateWithoutMilliseconds = [strEndDate stringByReplacingOccurrencesOfString:#"\\.\\d+" withString:#"" options:NSRegularExpressionSearch range:NSMakeRange(0, strEndDate.length)];
NSString *dateWithTimeZone = [NSString stringWithFormat:#"%#%#", dateWithoutMilliseconds, strTimeZone];
NSDateFormatter *df = [[NSDateFormatter alloc] init];
df.locale = [NSLocale localeWithLocaleIdentifier:#"en_US_POSIX"];
df.dateFormat = #"yyyy-MM-dd HH:mm:ssZZZZZ"];
NSDate *newEndDate = [df dateFromString:dateWithTimeZone];
The question was actually similar to (What is the best way to deal with the NSDateFormatter locale "feechur"?) as was suggested originally, but it was this other question (NSDateFormatter fails to return a datetime for UK region with 12 hour clock set) which really made it click for me - its the UK region with the 12hour clock which causes the code to fail, but the dateFormatter was easily fixed by simply setting the locale to "un_US_POSIX" as suggested in the answer to that question (it was also suggested below by vadian - I did not try his code however). Thank you to everyone who contributed hints and leads!

Convert NSDate to Unix Time Stamp for use in Dictionary

While there are numerous examples on SO and the web of converting the current date to a unix timestamp, I can't seem to find one for any date.
This code produces error shown.
NSDate *date = self.datepicker.date;
time_t start = (time_t) [date timeIntervalSince1970];//collection element of time_t is not an objective-c object
Would appreciate any suggestions.
I believe that code will work and the error message relates to a different statement.
If you want to put that time_t into a dictionary then you'll need to wrap it in an NSNumber object. However you may as well keep it as an NSTimeInterval (double) and cast it when using it:
NSDate *date = self.datepicker.date;
NSTimeInterval start = [date timeIntervalSince1970]
dict[#"startTime"] = #(start);
However you can also cast it before adding it to the dictionary if you really want to.

Evernote search with date range

My objective is to display all notes created on date A, date B, date C etc.
I'm building an Evernote Query as such:
//for all notes created on 2015 May 11
ENNoteSearch *searchMayEleven = [ENNoteSearch noteSearchWithSearchString: #"created:20150511 -created:20150512"];
[[ENSession sharedSession] findNotesWithSearch:searchMayEleven
inNotebook:nil
orScope:ENSessionSearchScopeAll
sortOrder:ENSessionSortOrderRecentlyCreated
maxResults:100
completion:^(NSArray *findNotesResults, NSError *findNotesError) {
//completion block
}]];
My results, however, fetch notes that are created on 12 May as well as 11 May.
1) I deduce that I have to set a timezone in my Evernote Session. Based on your experience, is this a valid deduction?
2) If so, I haven't been able to find a way to do so after reading through the documentation. Is it even possible?
3) Would you advice an alternative approach? Perhaps using the notestore instead?
In Evernote your dates are being kept in UTC.
When you make the search you need to create an Evernote search grammar that's relative to the timezone that you're interested in. In your case the timezone of the client or of the iPhone.
To get the user timezone:
ENSession * session = [ENSession sharedSession];
EDAMUser * user = session.user;
where the EDAMUser class has this structure:
#interface EDAMUser : FATObject
#property (nonatomic, strong) NSNumber * id; // EDAMUserID
#property (nonatomic, strong) NSString * username;
...
#property (nonatomic, strong) NSString * timezone;
For example my user timezone is: America/Montreal so on EST.
In order to get all the notes created May 11th you need to construct this Evernote search grammar:
#"created:20150511T040000Z -created:20150512T040000Z"
notice the ...T040000Z at the end.
So the conclusion is that you need to include the "definition" of the date from the client's perspective otherwise the query will work on UTC.
Here is an example of how to build the Evernote grammar search for the current day:
-(NSString *)buildQueryStringForDate: (NSDate *)date {
NSDateFormatter * formatter = [NSDateFormatter new];
[formatter setDateFormat:#"yyyyMMdd'T'HHmmss'Z'"];
formatter.timeZone = [NSTimeZone timeZoneWithName:#"UTC"];
formatter.locale = [NSLocale systemLocale];
DateRange * dateRange = [DateRange rangeForDayContainingDate:[NSDate new]];
return [NSString stringWithFormat:#"created:%# -created:%#", [formatter stringFromDate:dateRange.startDate], [formatter stringFromDate:dateRange.endDate]];
}
The code for [DateRange rangeForDayContainingDate:[NSDate new]] can be found here: How can I generate convenient date ranges based on a given NSDate?
I hope this helps.
It sounds like this might be a time zone issue. The fact that notes from the previous day are being surfaced could be explained by the fact that the search you are performing checks the time as reported by the client (usually the local time zone of the client) and not UTC or any well-defined time zone.
Your existing search grammar: created:20150511 -created:20150512 should return notes created after May 11 and before May 12th utilizing the time and date on the client that was used when the note was created. To force the search to use absolute time for when a note was created and not the created time as reported by the Evernote client you must use the Z postfix to the date-time stamp as seen in the following search grammar which will you return notes created only on May 15, 2015 UTC:
created:20150511T000000Z -created:20150512T000000Z
Sources
https://dev.evernote.com/doc/articles/search_grammar.php
https://dev.evernote.com/doc/reference/Types.html#Struct_Note
Given the time constraint on hand, I am deploying the following solution:
-(NSString *)buildQueryStringForDate: (NSDate *)date {
NSDateFormatter *dateFormat = [[NSDateFormatter alloc] init];
NSDate *dateAfter = [date dateByAddingDays:1];
NSTimeZone *currentTimeZone = [NSTimeZone localTimeZone];
[dateFormat setDateFormat: #"'created:'YYYYMMdd'T'HHmmss"];
[dateFormat setTimeZone:currentTimeZone];
NSString *searchString = [NSString stringWithFormat: #"%# -%#", [dateFormat stringFromDate:[date dateByAddingTimeInterval: currentTimeZone.secondsFromGMT]], [dateFormat stringFromDate:[dateAfter dateByAddingTimeInterval: currentTimeZone.secondsFromGMT]]];
NSLog(#"%#",searchString);
return searchString;
}
In all, it's a hack using NSDate instance method of secondsFromGMT to offset the timezone difference. Does not really use the correct concepts. but it'd have to do for now.
Any comments will be warmly welcomed :)

Hardware-dependent NSDateFormatter dateFromString: bug (returns nil)

I have several date strings that I need to convert to NSDates.
My parsing code is the following:
NSString *s = [pair objectForKey:#"nodeContent"];
NSDateFormatter *f = [[NSDateFormatter alloc] init];
[f setDateFormat:#"yyyy-MM-dd'T'HH:mm:ssZZ"];
self.date = [f dateFromString:s];
The above code works fine in all the devices and simulators we've tested.
The strange thing is that when the above code runs on any iPhone 5 running iOS 6.1 or 7.0.x , the line self.date = [f dateFromString:s]; returns nil every time.
I have checked and the string s exists and contains the same characters when compared side-by-side with a device that does parse the date correctly.
This is an example date string:
`2013-10-31T21:50:00-06:00'
Am I missing something here?
It's because you are not setting the date formatter's locale to the special en_US_POSIX locale. Most likely your iPhone 5 has a different setting for the 24-hour setting.
You need to set the special locale whenever you parse a fixed format string.

Xcode - Get Current date and time from a server(like time.is) and convert it to NSDate

i don't want to get the current date from the users device, because the user can edit the date.
i would like to get the current date and time from a server like time.apple.com or time.is and then convert it to an NSDate. How?
You can first get the date in the form of a string by hitting the url (if the webservice is giving it as a string). And then using date formatter you could make the string into an NSDate.
For instance:
NSURL *url = [NSURL URLWithString:#"http://yourtimeurl"];
NSString *str = [[NSString alloc] initWithContentsOfURL:url usedEncoding:Nil error:Nil];
assume you are getting the date in the format dd-MM-yyyy, then
NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
dateFormatter.dateFormat =#"dd-MM-yyyy";
NSDate *date = [dateFormatter dateFromString:str];
But most probably when you hit your url, you might get some data structure like a json which you would have to parse. And most probably the date wouldn't be returned in the above format. But now you know how to go forward. Make the appropriate changes.
Also initWithContentsOfURL: is a synchronous call. It's recommended that you use a NSURLConnection for this and make asynch call to your webservice.
This might be useful:
http://www.earthtools.org/webservices.htm#timezone --xmlresponse
http://www.timeapi.org/utc/now --string

Resources