Thursday, January 10, 2013

Creating a simple ios app with the Date Picker to find what day is it

From the above heading, you might think how stupid it is to make an app to find out the date without checking out the calendar :p It's not what I really mean here. 

I am going to use the UIDatePicker controller to let the user select a preferred date from it and check out what day of the week it is e.g:- if you select your birthday, it should tell you on what day of the week you are born. Interesting, isn't it. It's also simple because it's not even complex as using datasources and delegates as we did discuss in the UIPickerView post.

The design is simple as always, you will understand it from the below diagram

 you have a Date Picker added to your screen. Make sure to select it -->  go to Attributes inspector and select the Mode to Date to let  the user select the day, month and the year only.

You need to have one more button to let the user click after selecting a date.

All the rest are the icing for the app screen :)

now examine the code of the header file below

//  MyDatePickerAppViewController.h

#import <UIKit/UIKit.h>

@interface MyDatePickerAppViewController : UIViewController {
    IBOutlet UIDatePicker *dp;        // an object of UIDatePicker to deal with its functions

@property(nonatomic,retain) UIDatePicker *dp;

-(IBAction) displayDay;                //a method for the button click


Next, let's move to the implementation file

//  MyDatePickerAppViewController.m

#import "MyDatePickerAppViewController.h"

@implementation MyDatePickerAppViewController

- (void)dealloc
    [super dealloc];

- (void)didReceiveMemoryWarning
    [super didReceiveMemoryWarning];

#pragma mark - View lifecycle

- (void)viewDidUnload
    [super viewDidUnload];

- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation
    return (interfaceOrientation == UIInterfaceOrientationPortrait);

@synthesize dp;

-(IBAction) displayDay
    NSDate *;              // gives the selected date which is an NSDate object
    NSDateFormatter *formatter=[[NSDateFormatter alloc] init];  //creating an NSDateFormatter object
    [formatter setDateFormat:@"EEEE"];                        //we are going to format the date in IEEE standard
//find the chosen day's day in the week and get it to a string
    NSString *weekDay=[formatter stringFromDate:chosen]; 
//format a message
    NSString *msg=[[NSString alloc] initWithFormat:@"The day is %@",weekDay];
//view the message in an alert box
    UIAlertView *alert=[[UIAlertView alloc] initWithTitle:@"What day is it?" message:msg delegate:nil cancelButtonTitle:@"Okay" otherButtonTitles:nil, nil];
    [alert show];
    [alert release];
    [msg release];
    [formatter release];    


Output of the app is as following

Now you can build and run your app. I also have made available the project source code for you.