Rahul Gupta
Rahul Gupta

Reputation: 808

calculating timestamp in iOS for core data project

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.

Upvotes: 2

Views: 4277

Answers (2)

Rahul Gupta
Rahul Gupta

Reputation: 808

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

Upvotes: 0

pedros
pedros

Reputation: 1197

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

Upvotes: 6

Related Questions