Accurate time on iPhone - ios

Is there an way to get a time very precisely in iPhone.? Currently i am trying with the ios NTp client Here . I am getting almost 600 milliseconds difference while comparing with different divices . Even i am not worrying about the accurate time like ntp , I want to show same time with milliseconds in different devices.

Check out this NTP client library for iOS: https://code.google.com/p/ios-ntp/
Source: 1

This is simple way to do this go through it :-
+ (NSDate *) GMTNow
{
NSDate *sourceDate = [NSDate date];
NSTimeZone* currentTimeZone = [NSTimeZone localTimeZone];
NSInteger currentGMTOffset = [currentTimeZone secondsFromGMT];
[sourceDate dateByAddingTimeInterval:currentGMTOffset];
return sourceDate;
}

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 :)

How to get timezones and their respective offset to display on a table view?

I need to display list of available times zones and their respective offset on a table view like this;
eg: Asia/Colombo - 5
I've got list of times zones using the below code.
NSArray *timezoneNames = [NSTimeZone knownTimeZoneNames];
for (NSString *timesZoneName in [timezoneNames sortedArrayUsingSelector:#selector(compare:)])
{
NSLog(#"%#",timesZoneName);
}
further, I used following code to get the offset from the local time zone.
NSTimeZone *timeZones = [NSTimeZone localTimeZone];
NSInteger offset = [timeZones secondsFromGMT]/3600.0;
NSString *tzname = [timeZones name];
NSLog(#"Time Zone Name: %# - %ld", tzname, offset);
but cannot find a way around how to get the offset values from the names. If anyone can guide me how to do it please ?
Well you were 1/2 the way there - you need to actually instantiate the TimeZone from the name of the timezone in order to calculate it's offset, so code like:
NSArray *timezoneNames = [NSTimeZone knownTimeZoneNames];
for (NSString *timesZoneName in [timezoneNames sortedArrayUsingSelector:#selector(compare:)])
{
NSTimeZone *timeZone = [[NSTimeZone alloc] initWithName:timesZoneName];
NSInteger offset = [timeZone secondsFromGMT]/3600.0;
NSString *tzname = [timeZone name];
NSLog(#"Time Zone Name: %# - %ld", tzname, offset);
}
i.e. use [[NSTimeZone alloc] initWithName:timesZoneName] to get the timezone that's named; then you can get the offset.
Bear in mind that not all timezone offsets are on a whole-hour boundary. For example India Standard Time is 5.5 hours off of GMT.

How can I get the fileCreationDate to an accuracy of 6 decimal places when converted using timeIntervalSince1970?

How can I get the fileCreationDate for a file stored in the NSDocumentsDirectory to an accuracy of 6 decimal places when converted to an NSTimeInverval?
Some code:
//Not accurate enough:
NSDictionary* fileAttribs = [[NSFileManager defaultManager] attributesOfItemAtPath:myPhotoPath error:nil];
NSDate *creationDateOfPhoto = [fileAttribs fileCreationDate];
NSTimeInterval creationDateAsTimeInterval = [creationDateOfPhoto timeIntervalSince1970];
NSLog(#"Creation Date of Photo As Time Interval Since 1970: %f", creationDateAsTimeInterval);
//With the desired accuracy:
NSDate* now = [NSDate date];
NSTimeInterval nowStampAsTimeInterval = [now timeIntervalSince1970];
NSLog(#"Now As Time Interval Since 1970: %f", nowStampAsTimeInterval);
A sample output from this code is:
Creation Date of Photo As Time Interval Since 1970: 1373022866.000000
Now As Time Interval Since 1970: 1373022884.294028
Is it possible or is it a limitation of storage in NSDocuments?
It's a OS level limitation. HFS+, the file system which is used by iOS, has a date resolution of one second - this is why all your file timestamps are whole seconds. Sub second precision isn't supported. Sorry!

Resources