Date formatters format the textual representation of cells that contain date objects (including Gregorian dates), and convert textual representations of dates and times into date objects.” – Apple Documentation.

While creating an app, you generally come across a situation, when you require custom date format to represent dates in user friendly manner. For this purpose, Cocoa provides date formatter class. Using a date formatter, we can express dates colloquially, such as “today,” “day after tomorrow,” and “a month from today.”

Here’s the example of date formatter:
NSDateFormatter *dateFormatter = [[[NSDateFormatter alloc]initWithDateFormat:@”%1m/%1d/%Y” allowNaturalLanguage:NO] autorelease];

NSDate *date = [NSDate dateWithTimeIntervalSinceReferenceDate:118800];


NSString *formattedDateString = [dateFormatter stringFromDate:date];


NSLog(@”formattedDateString: %@”, formattedDateString);

// Output: formattedDateString: 1/2/2001

Below is the list of possible date conversions using date formatter (More detail on date conversion and range of conversions can be found here):

Specifier

Description

%%

A '%' character

%a

Abbreviated weekday name

%A

Full weekday name

%b

Abbreviated month name

%B

Full month name

%c

Shorthand for “%X %x“, the locale format for date and time

%d

Day of the month as a decimal number (01-31)

%e

Same as %d but does not print the leading 0 for days 1 through 9 (unlike strftime(), does not print a leading space)

%F

Milliseconds as a decimal number (000-999)

%H

Hour based on a 24-hour clock as a decimal number (00-23)

%I

Hour based on a 12-hour clock as a decimal number (01-12)

%j

Day of the year as a decimal number (001-366)

%m

Month as a decimal number (01-12)

%M

Minute as a decimal number (00-59)

%p

AM/PM designation for the locale

%S

Second as a decimal number (00-59)

%w

Weekday as a decimal number (0-6), where Sunday is 0

%x

Date using the date representation for the locale, including the time zone (produces different results from strftime())

%X

Time using the time representation for the locale (produces different results from strftime())

%y

Year without century (00-99)

%Y

Year with century (such as 1990)

%Z

Time zone name (such as Pacific Daylight Time; produces different results from strftime())

%z

Time zone offset in hours and minutes from GMT (HHMM)

Hope this helps you in programming. Do let me know your views on it.

Enjoy Coding!


One thought on “Date formatting in Cocoa

  1. Excellent issues altogether, you simply won a emblem new reader. What would you recommend about your submit that you simply made a few days ago? Any certain?

Leave a Reply to Dess Cancel reply

Your email address will not be published. Required fields are marked *