Objective-C – Display Date and Time Using NSDateFormatter

You can get the Date and Time in NSString using NSDateFormatter.

// Get current datetime
NSDate *currentDateTime = [NSDate date];

// Instantiate a NSDateFormatter
NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];

// Set the dateFormatter format
[dateFormatter setDateFormat:@"yyyy-MM-dd HH:mm:ss"];

// Get the date time in NSString
NSString *dateInString = [dateFormatter stringFromDate:currentDateTime];

// Release the dateFormatter
[dateFormatter release];


 
More examples of date format patterns:
yyyy.MM.dd G ‘at’ HH:mm:ss zzz

  • 1996.07.10 AD at 15:08:56 PDT

EEE, MMM d, ”yy

  • Wed, July 10, ’96

h:mm a

  • 12:08 PM

hh ‘o”clock’ a, zzzz

  • 12 o’clock PM, Pacific Daylight Time

K:mm a, z

  • 0:00 PM, PST

yyyyy.MMMM.dd GGG hh:mm aaa

  • 01996.July.10 AD 12:08 PM

 

The above examples are found in Unicode Technical Standard #35. But it is found that Apple is not 100% conform to the standard. More examples can be found at Format String for the iPhone NSDateFormatter.

Done =)
 

Reference:

4 thoughts on “Objective-C – Display Date and Time Using NSDateFormatter”

Leave a comment

This site uses Akismet to reduce spam. Learn how your comment data is processed.