0

How do I get date from the day of the year? for e.g., if I give day as "1" then date should be "January 1"

How do I get that in iPhone? I have found answer in javascript but I want to know how to do the achieve same thing in Objective?

Bharath
  • 3,001
  • 6
  • 32
  • 65

2 Answers2

2

I guess this code will work for you: I have created a sample function where a textfield gives input values for how many days to add. And a button to calculate final day. Here is the button event logic.

  NSDateComponents *dateComponent = [[NSDateComponents alloc] init];
  NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
  [formatter setDateFormat:@"yyyy-mm-dd"];

  NSDate *newDate =  [formatter dateFromString:@"2012-01-01"];

  // add days to current date
  dateComponent.day = [dayTextField.text intValue];

  // get a new date by adding components
  newDate = [[NSCalendar currentCalendar] dateByAddingComponents: dateComponent toDate:newDate options:0];

  [finalDate setText:[NSString stringWithFormat:@"%@", newDate]];

Here dayTextField.text is the text which says how many number of days want to calculated. (For example 125 days) and finalDate is an label which displays final generated date (means date after 125 days since 1 Jan 2012).

Benefit of this code is, any time you can change the start day parameter. For example, for other requirement, i need to count my days from "31 May 1999" then i will change it easily in one line and the same code will work.

Enjoy Coding :)

Mrunal
  • 13,982
  • 6
  • 52
  • 96
1
NSCalendar *gregorian =
   [[NSCalendar alloc] initWithCalendarIdentifier:NSGregorianCalendar];
NSUInteger dayOfYear =
   [gregorian ordinalityOfUnit:NSDayCalendarUnit
    inUnit:NSYearCalendarUnit forDate:[NSDate date]];
[gregorian release];
return dayOfYear;

Take from the post: How do you calculate the day of the year for a specific date in Objective-C?

Community
  • 1
  • 1
talbright
  • 446
  • 1
  • 10
  • 18
  • If you find another SO question that's identical, the thing to do is flag this question as a duplicate. :) – Almo Aug 01 '12 at 13:46
  • And this answer is the complete opposite of what the question was asking for. *And the cycle is complete* – WDUK Nov 27 '12 at 16:08