Search code examples
iosnsdatenstimeinterval

How to get and convert back user's birthdate to/from a NSTimeInterval?


Suppose, my birthdate is (mon/day/year) 10-05-1932 (as NSDate), how to convert this to NSTimeInterval.

Again, how to convert back that NSTimeInterval to NSDate back?

I tried using different methods of NSDate but haven't succeed yet.

What I'm doing?

NSString *strdate = @"10-05-1932";
NSDateFormatter *df = [[NSDateFormatter alloc] init];
[df setDateFormat:@"MM-dd-yyyy"];
NSDate *date = [df dateFromString:strdate];
NSLog(@"%.f", -[date timeIntervalSinceNow]);

This logs 2616605071 (as on 4th September 2015 at 16:21) – When I checked it with the site like this it gives me wrong date.


Solution

  • This is just worked!

    NSString *strdate = @"10-05-1932";
    NSDateFormatter *df = [[NSDateFormatter alloc] init];
    [df setDateFormat:@"MM-dd-yyyy"];
    NSDate *date = [df dateFromString:strdate];
    NSLog(@"%@",date);
    NSTimeInterval interval = [date timeIntervalSince1970];
    NSLog(@"%f", interval);
    NSDate *date2 = [NSDate dateWithTimeIntervalSince1970:interval];
    NSLog(@"%@",date2);
    

    Thanks to @sikhapol