Handling DateTime in Objective-C - How to get Current DateTime
Sometimes it is a bit non-trivial to developers coming to Objective-C from more common Java or C# how to deal with simple things. This post is about handling DateTime and I will illustrate dealing with it with a simple example.
How to get current DateTime
-(NSDateComponents *) getCurrentDateTime
{
    NSDate *now = [NSDate date];
    NSCalendar *cal = [NSCalendar currentCalendar];
    NSDateComponents *cmpnnts = [cal components : 
        NSHourCalendarUnit + NSMinuteCalendarUnit + NSSecondCalendarUnit fromDate : now];
    return cmpnnts;
}
For those used to work with Unix timestamps it will be easier to get current time in milliseconds, in Objective-C it is like so:
double nowMillis = 1000.0 * [[NSDate date] timeIntervalSince1970];
Enjoy :)
Tuesday, May 10, 2011 8:51 PM
 
                    
