Tuesday, June 10, 2014

A Code Snippet For Converting NSDate To NSString With NSDateFormatter

When working on programs that manipulate Dates sometimes those days need to be store & printed in particular format. iOS has given NSDate for date and time related data handling and  NSDateFormatter can be used to give a date of NSDate object a visual form. 

Code

Current Date and Time is obtained by init method of NSDate.

NSDate *date = [[NSDate allocinit];

Create a NSDateFormatter for set the date format that is needed to print and get a NSString object from the date.

NSDateFormatter *dateFormatter = [[NSDateFormatter allocinit];

Use setDateFormat of NSDateFormatter to get a date format that is needed to display. This method get the required date format by using NSString parameter and returns nothing.  The method has been called on the object dateFormatter.

[dateFormatter setDateFormat:@"dd-MM-YYYY HH:mm:ss"];

Method signature for setDateFormat

- (void)setDateFormat:(NSString *)string

NSString *dateString = [dateFormatter stringFromDate:date];

Invoke stringFromDate on dateFormatter object to get the the date value of NSDate object in specified date format. This method consumes previously created date object and assign a NSString represent of the date on date object to dateString.

Method signature for stringFromDate

- (NSString *)stringFromDate:(NSDate *)date

Print the dateString using  NSLog();

NSLog(@"The Date: %@", dateString);

Complete Code

    NSDate *date = [[NSDate alloc] init];
    NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
    [dateFormatter setDateFormat:@"dd-MM-YYYY HH:mm:ss"];
    NSString *dateString = [dateFormatter stringFromDate:date];

    NSLog(@"The Date: %@", dateString);