calculating timestamp in iOS for core data project - iphone

I am using core data in my project. Database is sqlite and there is column for storing "birthdate" having datatype "timestamp".
Now, I want to insert some records in it and I am having dates in human readable format like "1809-06-17".
How to convert this date to timestamp so that, I get this date when fetched from database.
I tried some conversions using python script, but I got different results.
Is there any easy way to do this? Please help me.

You could store the date as TEXT and dont have to worry about converting to and from timestamp.
To convert timestamp to NSDate use:
NSDate *date = [NSDate dateWithTimeIntervalSince1970:timeStamp];
NSLog(#"%#", date);
String to NSDate to timestamp:
NSDate *date = [NSDate dateWithString:stringWithDate];
NSTimeInterval timeStamp = [date timeIntervalSince1970];
SQLite doesnt have a datatype for Date, it just stores it in a INT (Unix Time), REAL(Julian day numbers) or TEXT(ISO8601 strings) depending on what you choose.
So you could just store the date in the format you already have ("1809-06-17") as a TEXT column or you store as a timestamp in an INT column using the methods above to convert both ways.
SQLite Date and Time functions: SQLite date and time
SQLite DATATYPES: SQLite datatypes doc
SQLite Oficial Site and Documentation: SQLite Home
Hope you can solve your problem

Finally I got the solution I needed.
NSDateFormatter *df = [[NSDateFormatter alloc]init];
[df setDateFormat:#"yyyy-MM-dd"];
NSDate * past = [df dateFromString:#"1971-04-06"];
NSTimeInterval oldTime = [past timeIntervalSinceDate:[df dateFromString:#"2001-01-01"]];
NSString * unixTime = [[NSString alloc] initWithFormat:#"%0.0f", oldTime];
NSLog(#"unixTime = %#",unixTime);

Related

Convert timestamp into NSDate

I am parsing a JSON file which contains a timestamp. I want to convert this timestamp into an NSDate.
My code :
NSString *depart=[alternates valueForKey:#"startTime"];
NSTimeInterval intervaldep=[depart doubleValue];
NSDate *myDate = [NSDate dateWithTimeIntervalSince1970:intervaldep];
But I am getting wrong date, e.g.: 44135-04-01 03:20:00 +0000 for time stamp 1330606668000.
If any one has any idea please help.
Thank you.
Your timestamp contains milliseconds, just divide your timestamp by 1000 (i.e. trim the last three zeros) and you should be fine.
Try to add the NSTimeZone to your NSDate, by default the dates are in GMT0
You can check the syntax here:
Convert UTC NSDate to local Timezone Objective-C

Storing NSDate with system time zone in Core Data

When I store a date in CoreData as [NSDate date], it is saved -5:30 difference. In core data I used attribute type as date.
How to store NSdate with timeZone?
Update: Here is the code I am using:
To store the date:
database = (DataBase*) [fetchResults objectAtIndex:indexVal];
[database setDate:[NSDate date]];
NSError error = nil;
[managedObjectContext save:&error]
To retrieve the date:
DataBase *newDataBase = (DataBase) [fetchResults objectAtIndex:i];
NSDate *RetrivedDate = [newDataBase Date];
NSLog(#"Retrived Date :",RetrivedDate");
Before storing I log it. It shows current date and time. After storing I immediately fetched the date . but it showed 1 day delayed date..
NSDate doesn't have a time zone. It stores dates as a number of seconds since a reference date in GMT.
The time zone is applied when you format the date for display using NSDateFormatter. This will pick up the device time zone by default.

date from API in decimal?

Might not be unrelated, but if you go to this link. The date_latest_message is in decimal, how can I convert that to today's date and time in iPhone?
It looks like that api uses timestamp for transmitting dates. It seems +dateWithTimeIntervalSince1970 function returns result that looks correct, so parse that decimal value and try the following to get date object:
NSTimeInterval creationDate = 1298389881.0542741;
NSDate *date = [NSDate dateWithTimeIntervalSince1970: creationDate];
Then you can use NSDateFormatter class to format that date to any readable representation you want.

iPhone SQLite date problem

Database gets created just fine, and the insert works just fine. I'm having problem with the select statement below. It returns no records and no error. A select on any other field works just fine. Can anyone spot what I'm doing wrong?
"create table if not exists data (pkey integer primary key, doc date)"
[db executeUpdate:#"insert into data ( doc) values (?)" , [NSDate date]];
"select * FROM data WHERE doc between '2009-08-23' and '2009-08-23' "
The part between '2009-08-23' and '2009-08-23' is always false, because that's a range of zero time, for lack of a better description.
If you want items occurring on exactly 2009-08-23, select between '2009-08-23' and '2009-08-24' which will range from midnight on the 23rd to midnight on the 24th.
Here's an example of this in action:
sqlite> CREATE TABLE t (d DATETIME);
sqlite> SELECT DATETIME('now');
2009-08-24 02:32:20
sqlite> INSERT INTO t VALUES (datetime('now'));
sqlite> SELECT * FROM t;
2009-08-24 02:33:42
sqlite> SELECT * FROM t where d BETWEEN '2009-08-24' and '2009-08-24';
sqlite> SELECT * FROM t where d BETWEEN '2009-08-24' and '2009-08-25';
2009-08-24 02:33:42
I have had to do this exact type of lookup on sqlite and here is a simple date formatting example to get the start and end of day timestamps for your date.
In my case I am storing the timestamps with this timestamp format in sqlite: "yyyy-MM-dd HH:mm:ss.SSSS". This example uses the current date ([NSDate date]).
NSDateFormatter *dateFormatter = [[[NSDateFormatter alloc] init] autorelease];
[dateFormatter setDateFormat:#"yyyy-MM-dd"];
NSString *dateString = [dateFormatter stringFromDate:[NSDate date]];
NSDate *startOfDay = [dateFormatter dateFromString:dateString];
// add a full day and subtract 1 second to get the end of day timestamp
NSDate *endOfDay = [startOfDay addTimeInterval:(60*60*24)-1];
[dateFormatter setDateFormat:#"yyyy-MM-dd HH:mm:ss.SSSS"];
You can then use startOfDay and endOfDay for your query values.
SQLite does string comparison, not date comparison.
So, one way to solve your problem is:
"select * FROM data WHERE doc between '2009-08-23' and '2009-08-23 99' "

sqlite datetime data type with iphone NSdate?

Is there a way in sqlite to automatically save a timestamp in the table whenever a record has been created that I can then grab and save as an NSDate in my application?
Or should I instead create the NSdate object with the current time in my iphone app, and then insert it into the database. If so? What column should the datatype be for the time? a DATETIME?
What I do is use sqlite's current_timestamp (which looks something like this: 2009-06-16 12:11:24). To do this just set the row type of your qslite table to
Data type: "DATETIME"
Allow null: NO
Default value: CURRENT_TIMESTAMP
Then use an SQL query like this:
#"INSERT INTO 'scores' ('one', 'two', 'three') VALUES ('%d', '%d', '%d')"
ignoring the date, so that it will automatically get the current time value.
Then to convert this to an NSDate you can use an NSDateFormatter like this:
NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
[formatter setDateFormat:#"yyyy-MM-dd HH:mm:ss"]; //this is the sqlite's format
NSDate *date = [formatter dateFromString:score.datetime];
and now you have that date as an NSDate object. Just don't forget to release the NSDateFormatter we allocated :)
There is no TIMESTAMP datatype that you can use in SQLite, so you'll have to manually insert the time when you do your INSERT. I use the INTEGER datatype in the database, and convert my NSDate as such:
sqlite3_bind_double(insert_statement, 1, [myDate timeIntervalSince1970]);
And to get it back out of the DB:
myDate = [NSDate dateWithTimeIntervalSince1970:sqlite3_column_double(select_statement, 1)];
I like to use the sqlite julianday() function, like:
insert into foo(currentDate) values (julianday('now'));
This would be inserting a floating point value into foo.currentDate.
You might also find some details of this question/answer useful.
How get a datetime column in SQLite with Objective C