Dates and times in Objective-C

NSDate and NSDateFormatter classes provide the features of date and time.

NSDateFormatter is the helper class that enables easy conversion of NSDate to NSString and vice versa.

A simple example to show conversion of NSDate to NSString and back to NSDate is shown below.

#import <Foundation/Foundation.h>

int main() {
   NSAutoreleasePool * pool = [[NSAutoreleasePool alloc] init];
   NSDate *date= [NSDate date];
   NSDateFormatter *dateFormatter = [[NSDateFormatter alloc]init];
   [dateFormatter setDateFormat:@"yyyy-MM-dd"];
   NSString *dateString = [dateFormatter stringFromDate:date];
   NSLog(@"Current date is %@",dateString);
   NSDate *newDate = [dateFormatter dateFromString:dateString];
   NSLog(@"NewDate: %@",newDate);
   [pool drain]
   return 0;

Now when we compile and run the program, we will get the following result.

2013-09-29 14:48:13.445 Date and time[870] Current date is 2013-09-29
2013-09-29 14:48:13.447 Date and time[870] NewDate: 2013-09-28 18:30:00 +0000

As we can see in the above program, we get the current time with the help of NSDate.

NSDateFormatter is the class that is taking care of converting the format.

The date format can be changed based on the available data. For example, when we want to add time to the above example, the date format can be changed to @"yyyy-MM-dd:hh:mm:ss"