Convert NSDate to Unix Time Stamp for use in Dictionary - ios

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.

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!

How to get int value of time stamp which includes milliseconds in objective c

NSNumber * uniqueId = [NSNumber numberWithInt:([[NSDate date] timeIntervalSince1970])];
Milliseconds is not included in the above code.If i used like below code ,it is printing negative values.
NSNumber * uniqueId1 = [NSNumber numberWithInt:([[NSDate date] timeIntervalSince1970] * 1000)];
Can we get time stamp with milliseconds as int????
#AnjaniG you can use one of them..
NSString *strTimeStamp = [NSString stringWithFormat:#"%f",[[NSDate date] timeIntervalSince1970] * 1000];
int timestamps = [strTimeStamp intValue];
NSLog(#"number int = %d",timestamps);
You should not use an Int, [[NSDate date] timeIntervalSince1970] * 1000 is bigger than INT_MAX. You should use long long to store the value.
NSNumber * uniqueId1 = [NSNumber numberWithLongLong:([[NSDate date] timeIntervalSince1970] * 1000)];
The problem is that you are casting a floating point to an integer.
As per the documentation, timeIntervalSince1970 returns an NSTimeInterval, which is a double, not an integer.
In your first code example, you're actually discarding the milliseconds by casting.
In your second code example, you are overflowing the integer. After multiplying the value by 1000, it is too large to fit in an integer.
In the end, you're just doing too much code and you shouldn't need to really worry about this.
NSTimeInterval interval = [NSDate date].timeIntervalSince1970;
NSNumber *timestamp = #(interval * 1000.);
Here, I use the proper documented type of NSTimeInterval. Then I multiply that by 1,000 to change seconds to milliseconds. Finally, I use Clang literal syntax to instruct the compiler to create the appropriate NSNumber.

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

Create a date from a string

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.

Incompatible pointer types initializing 'NSDate

I am setting up some constants, one being an NSDate but receiving this wanring message:
Incompatible pointer types initializing NSDate *const __strong with an expression of type NSString
Simple explanation of code (imp file):
NSDate *const kPAPUserBirthdayKey = #"fbBirthday";
Advanced explanation:
I use a constants file as a singleton holding constant variables for the API i write to. For example the above which is a Date field which will hold the facebook users birthday when connecting to Facebook.
This is then later used in the following conversion:
// Convert the DOB string into Date format
NSDateFormatter* df = [[NSDateFormatter alloc] init];
[df setDateFormat:#"MM/dd/yyyy"];
NSDate* userDOB = [df dateFromString:user.birthday];
[[PFUser currentUser] setObject:userDOB forKey:kPAPUserBirthdayKey];
Can someone explain what the warning actually means and what should be changed here? I get the same error on the last line of the above?
NSDate *const kPAPUserBirthdayKey = #"fbBirthday";
You are assigning a string to a NSDate.
Change NSDate to NSString.
Use:
NSString const *kPAPUserBirthdayKey = #"fbBirthday";
Also check what you need ?
A constant pointer or pointer to a constant.
NSDate *const kPAPUserBirthdayKey = #"fbBirthday";
Here fbBirthday is a string not date. The warning says that.
Change your constant's type to NSString. The compiler is telling you you're making an assignment between incompatible types, as NSString is not a subclass of NSDate.

Resources