Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get start date of current year in iOS

I don't know how to use NSDate or NSCalendar in this condition.
Help me to solve this issue.

like image 869
Mihir Oza Avatar asked Dec 05 '22 21:12

Mihir Oza


2 Answers

This can be done much cleaner than the other answers:

NSDate *startOfYear;

[[NSCalendar currentCalendar] rangeOfUnit:NSCalendarUnitYear startDate:&startOfYear interval:0 forDate:[NSDate date]];

startOfYear now holds midnight at January 1st of the current year.

like image 95
mattsson Avatar answered Dec 23 '22 12:12

mattsson


-(NSDate *)getFirstDateOfCurrentYear
 {
  //Get current year
  NSDate *currentYear=[[NSDate alloc]init];
  currentYear=[NSDate date];
  NSDateFormatter *formatter1 = [[NSDateFormatter alloc] init];
  [formatter1 setDateFormat:@"yyyy"];
  NSString *currentYearString = [formatter1 stringFromDate:currentYear];

  //Get first date of current year
  NSString *firstDateString=[NSString stringWithFormat:@"10 01-01-%@",currentYearString];
  NSDateFormatter *formatter2 = [[NSDateFormatter alloc] init];
  [formatter2 setDateFormat:@"hh dd-MM-yyyy"];
  NSDate *firstDate = [[NSDate alloc]init];
  firstDate = [formatter2 dateFromString:firstDateString];

  return firstDate;
 }
like image 42
Britto Thomas Avatar answered Dec 23 '22 14:12

Britto Thomas