Header Ads

Data Storage - Date and Times - 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()
{
          NSDate *dateobj = [NSDate date];
          NSDateFormatter dateFormatter = [[NSDateFormatter alloc]init];
          [dateFormatter setDateFormat : @"yyyy-MM-dd"];
          NSString *dateString = [dateFormatter stringFormDate : dateobj];
          NSLog(@"Current date is %@", dateString);
          NSDate *newDate = [dateFormatter dateFromString : dateString];
          NSLog(@"NewDate : %@", newDate);
          return 0;
}

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

NSDateFormatter is the class that 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".

No comments:

Powered by Blogger.