Hemang
Hemang

Reputation: 27072

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.

Upvotes: 0

Views: 54

Answers (2)

Hemang
Hemang

Reputation: 27072

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

Upvotes: 0

yusuke024
yusuke024

Reputation: 2229

NSTimeInterval timeInterval = date.timeIntervalSinceReferenceDate;
NSDate *anotherDate = [NSDate dateWithTimeIntervalSinceReferenceDate: timeInterval];

Try the code below. date and anotherDate will be identical.

NSCalendar *calendar = [NSCalendar currentCalendar];
calendar.timeZone = [NSTimeZone timeZoneForSecondsFromGMT:0];
NSDateComponents *components = [[NSDateComponents alloc] init];
[components setDay:10];
[components setMonth:5];
[components setYear:1934];
NSDate *date = [calendar dateFromComponents:components];
NSLog(@"%@", date);
NSTimeInterval timeInterval = [date timeIntervalSinceReferenceDate];
NSDate *anotherDate = [NSDate dateWithTimeIntervalSinceReferenceDate:timeInterval];
NSLog(@"%@", anotherDate);

UPDATE:

It's incorrect because you get timestamp (time interval) from that website which use UNIX timestamp. Also, it's incorrect because you use timeIntervalSinceNow which will likely change every time you call the method because it's relative to the current time. If you want the date/time interval that compatible with that website. Use:

NSTimeInterval timeInterval = date.timeIntervalSince1970;
NSDate *anotherDate = [NSDate dateWithTimeIntervalSince1970:timeInterval];

You can copy the timeInterval from the code above (-1188000000) and paste it on the website and it will give you a correct date.

Internally, NSDate store time interval relative to reference date (Jan 1st, 2001). The website you mentioned is UNIX timestamp that relative to Jan 1st, 1970.

Upvotes: 2

Related Questions