0

I'm just learning Objective-C and Xcode and trying to make some simple apps.
I need to get today's day and month as ant int.
Example:
Todays day: 29/12/2013
(int) TodaysDay = 29;
(int) TodaysMonth = 1200; (1 - 100, 2 - 200, 3 - 300...)
(int) TodaysValue = TodaysDay + TodaysMonth; (in ex. 1229)
switch(TodaysValue)
case 1229:
do something.
I tried using this:

NSDate *today = [NSDate date];
NSDateFormatter *dateFormat = [[NSDateFormatter alloc] init];
[dateFormat setDateFormat:@"dd/MM"];
NSString *dateString = [dateFormat stringFromDate:today];  

Thank you for your help!
This works pretty well!

CFGregorianDate currentDate = CFAbsoluteTimeGetGregorianDate(CFAbsoluteTimeGetCurrent(), CFTimeZoneCopySystem());
TodaysDay = currentDate.day;
TodaysMonth = currentDate.month;
TodaysValue = TodaysDay + (TodaysMonth * 100);
sphynx
  • 413
  • 1
  • 7
  • 20

2 Answers2

4

Lookup the components:fromDate: method of NSCalendar - this will convert an NSDate object to an NSDateComponents object correctly, and the latter provides properties for the day and month you require.

CRD
  • 52,522
  • 5
  • 70
  • 86
0

After you get dateString, implement following expression as follows to get date and month as integer.

 NSArray *date = [dateString componentsSeparatedByString:@"/"];
 if ([date count] == 2)
 {
     NSUInteger day = [[date objectAtIndex:0] integerValue];
     NSUInteger month = [[date objectAtIndex:1] integerValue];
 }
ldindu
  • 4,270
  • 2
  • 20
  • 24
  • Ugh. This is overly complex,and also fragile. Date formats vary based on locale, so parsing the output of a date formatter as a string may break. CRDs recommendation of using NSCalendar and components:fromDate: is a much cleaner, more reliable way to do this. – Duncan C Dec 29 '13 at 17:52