Wednesday, August 5, 2009

Conversion of date and time to/from number of seconds from the reference date

A) Converting date to seconds


//Create nscomponents object
NSDateComponents *objNsComps = [[NSDateComponents alloc] init];
//set date
[objNsComps setDay:10 ];
[objNsComps setMonth:11];
[objNsComps setYear:2008];

//set time
[objNsComps setHour:10 ];
[objNsComps setMinute:15];
[objNsComps setSecond:20];
///conversion in NSdate object
NSCalendar *gregorian = [[NSCalendar alloc] initWithCalendarIdentifier:NSGregorianCalendar];
NSDate *objDate = [gregorian dateFromComponents: objNsComps];
//get number of seconds from refrence date 1 January 1970
///convert into double equibalent// time in secs
double dblSecs4Date = [objDate timeIntervalSince1970];
NSLog(@"dblSecs4DateFrmServer: %f", dblSecs4Date);
[gregorian release];
[objNsComps release];







B) Conversion of seconds into readable date string


double dblDateInSeconds = date in seconds from reference date 1 January 1970;
//Create NSDate Object
NSDate *objDate = [NSDate dateWithTimeIntervalSince1970: dblDateInSeconds];


NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
[dateFormatter setDateFormat:@"MM/dd/yyyy HH:mm:ss"];
//Convert in readable string
NSMutableString *strDate = [[[NSMutableString alloc] init] autorelease];
[strDate setString:@""];
[strDate appendString:[dateFormatter stringFromDate:objDate]];
[dateFormatter release];
NSLog(@"dateString: %@ ", strDate);

No comments:

Post a Comment