How to find date and time programmatically in different formats?

This post deals with finding out date and time programmatically in different formats.

Open .xib file

Drag 6 labels and arrange them as shown in figure

Name of the labels are

1)Date

2)label2

3)Time

4)label2

5]Date and Time with time zone

6)label3

Now come to .h file

Write the following highlighted lines of code

Now move to .m file

synthesize these labels

@synthesize label1,label2,label3;

Now in viewDidLoad function write the following code

NSDate *now = [[NSDate alloc] init];

	NSDateFormatter *df = [[NSDateFormatter alloc] init];

[df setDateFormat:@"yyyy-MM-dd"];
	NSString *date=[df stringFromDate:now];
	label1.text=date;
	 df = [[NSDateFormatter alloc] init];

	[df setDateFormat:@"hh:mm:ss a"];
	date=[df stringFromDate:now];
	label2.text=date;
	[df setDateFormat:@"yyyy-MM-dd hh:mm:ss a zzz"];
	date=[df stringFromDate:now];
	label3.text=date;

In the above code we can see that three different formats for date and time have been set. You can try your own format also for example “yyyy” will give only year.

Now  open Interface Builder and make connections as shown in figure

 

Save and build the application. You will get output like shown below