Click here to Skip to main content
15,891,409 members
Articles / All Topics

A Code Snippet For Converting NSDate To NSString With NSDateFormatter

Rate me:
Please Sign up or sign in to vote.
4.00/5 (1 vote)
16 Jun 2014CPOL 17.2K   2   1
This is a code snippet for converting NSDate to NSString with NSDateFormatter

Introduction

When working on programs that manipulate dates, sometimes those days need to be stored & printed in a 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.

C#
NSDate *date = [[NSDate alloc] init];

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

C#
NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];

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

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

Method signature for setDateFormat is as follows:

C#
(void)setDateFormat:(NSString *)string
NSString *dateString = [dateFormatter stringFromDate:date];

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

Method signature for stringFromDate is as follows:

C#
(NSString *)stringFromDate:(NSDate *)date

Print the dateString using NSLog();

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

Complete Code

C#
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); 
This article was originally posted at http://nipunswritings.blogspot.com

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)


Written By
Sri Lanka Sri Lanka
This member has not yet provided a Biography. Assume it's interesting and varied, and probably something to do with programming.

Comments and Discussions

 
QuestionThere is a lot more to say about it Pin
KarstenK27-Jan-15 4:16
mveKarstenK27-Jan-15 4:16 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.