Home Tutorial Iphone Examples Current Date iPhone SDK

 
 

Share on Google+Share on Google+
Current Date iPhone SDK
Posted on: April 28, 2010 at 12:00 AM
Advertisement
In this example, you'll find out how to get current date & day in iPhone SDK. We'll also write a method to print the day and date of weekend in the same week.

Current Date iPhone SDK

In this example, you'll find out how to get current date & day in iPhone SDK. We'll also write a method to print the day and date of weekend in the same week.

Hope you are familiar with the NSDateFormatter! If not lets first find out what is NSdateFormatter in iPhone SDK programming.

NSDateFormatter is used to represent the NSDate format in iPhone applications. Using this you can print the date in any format such as 26 april 2010 or 26/04/2010.

Code to set the date format in iPhone

NSDateFormatter *dateFormat = [[NSDateFormatter alloc] init];
[dateFormat setDateFormat:@"dd/MM/yyyy :EEEE"];

In this example, we aims to print the current day, current Date and first weekend day of the same week.

Just copy and paste the given code into your application viewDidLoad method and test the application it must print the value as given in the image.

Code to print current data, day and first weekend day

- (void)viewDidLoad {

[super viewDidLoad];

NSDate *today1 = [NSDate date];
NSDateFormatter *dateFormat = [[NSDateFormatter alloc] init];
[dateFormat setDateFormat:@"dd/MM/yyyy :EEEE"];

NSString *dateString11 = [dateFormat stringFromDate:today1];

NSLog(@"date: %@", dateString11);

//[dateFormat release];
NSCalendar *gregorian11 = [[NSCalendar alloc] initWithCalendarIdentifier:NSGregorianCalendar];

NSDateComponents *components1 = [gregorian11 components:NSWeekdayCalendarUnit | NSYearCalendarUnit | NSMonthCalendarUnit | NSDayCalendarUnit fromDate:today1];
[components1 setDay:([components1 day]-([components1 weekday]-1)+7)];

NSDate *beginningOfWeek1 = [gregorian11 dateFromComponents:components1];
NSDateFormatter *dateFormat_weekend = [[NSDateFormatter alloc] init];
[dateFormat_weekend setDateFormat:@"dd/MM/yyyy :EEEE"];
NSString *dateString_first = [dateFormat_weekend stringFromDate:beginningOfWeek1];

NSLog(@"Weekend: %@", dateString_first);

}

To print the first weekend in the same week
[components1 setDay:([components1 day]+([components1 weekday]+1))];

You can also write it as

[components1 setDay:([components1 day]-([components1 weekday]-1)+6)];

Download Code

Advertisement

Related Tags for Current Date iPhone SDK:


Follow us on Twitter, or add us on Facebook or Google Plus to keep you updated with the recent trends of Java and other open source platforms.

Posted on: April 28, 2010

Recommend the tutorial

Advertisements Advertisements
 

 

 

DMCA.com