Xcode get current date, month, year
Posted by in iPhone XCode February 28, 2011 6 Comments

This example will show how to get the current date, current month, current year in Xcode Iphone SDK.

1. Get the current DateTime (NSDate)
2. Convert it to an NSString
3. Split the NSString to an NSArray (by ‘space’)
4. Get first object of the NSArray
5. Again, split it to an NSArray (by ‘-’, hyphen)
6. Access the object at index 0,1,2 to get the current year, month, date respectively.

That’s all :)

Below is the example:

NSDate *now = [NSDate date];
 
NSLog(@"now: %@", now); // now: 2011-02-28 09:57:49 +0000 
 
NSString *strDate = [[NSString alloc] initWithFormat:@"%@",now];
NSArray *arr = [strDate componentsSeparatedByString:@" "];
NSString *str;
str = [arr objectAtIndex:0];
NSLog(@"strdate: %@",str); // strdate: 2011-02-28
 
NSArray *arr_my = [str componentsSeparatedByString:@"-"];
 
NSInteger date = [[arr_my objectAtIndex:2] intValue];
NSInteger month = [[arr_my objectAtIndex:1] intValue];
NSInteger year = [[arr_my objectAtIndex:0] intValue];
 
NSLog(@"year = %d", year); // year = 2011
NSLog(@"month = %d", month); // month = 2
NSLog(@"date = %d", date); // date = 2

Hope it helps :)

Hoan Huynh is the founder and head of 4rapiddev.com. Reach him at hoan@4rapiddev.com
  • http://4rapiddev.com User

    Its awesome. Appreciate your sharing :)

    • hoanhuynh

      Wow, Comment was super fast. Thank you.

  • miwi

    very useful! thanks!!

  • http://www.facebook.com/profile.php?id=1437916220 Agustín Jaimes Vázquez

    Very useful… Thank you :)

  • Stecowell

    Excellent, thanks for sharing this.

  • Ben

    Amazing, thanks so much