How to get all the days/dates in current week, thi

2019-03-03 20:33发布

问题:

In my application i have to show list of working hours by date in a table view,

Here i have 5 scenarios

  1. Today's projects, working hours
  2. Selected date projects, hours
  3. Cureent week (sunday-saturday)
  4. Current month (working hours in january, February if it is feb march if it is march)
  5. Current year (all working hours in 2013)

i have implemented sqlite queries as follows,

1. Select Date, ProjectTitle, WorkingHours, sum(WorkingHours) from ProjDetailsTable where date = toDaysDate

2. Select Date, ProjectTitle, WorkingHours, sum(WorkingHours) from ProjDetailsTable where date = selecteDate

I have done for the fist two scenarions

For the 3,4,5 scenarios


3. Select Date, ProjectTitle, WorkingHours, sum(WorkingHours) from ProjDetailsTable where 
Date between two Dates

But My problem is if I have the dates

Is there any logic to get the starting for
current week, current month, current year

Note : not the 7 days back, not the 30 months back and not the 365 days back.

My requirement is:

if Current date is Feb-13-2020 WednesDay

This week: Feb-9 to Today

This Month: Feb-1 to Today

This Year: Jan-1-2020 to Today

回答1:

I hope this will give you basic idea how you have to proceed: For other scenarios you can work out

- (NSDate *)firstDayOfWeekFromDate:(NSDate *)date {
      NSCalendar* calendar = [NSCalendar currentCalendar];
      NSDateComponents* comps = [calendar components:NSYearForWeekOfYearCalendarUnit |NSYearCalendarUnit|NSMonthCalendarUnit|NSWeekCalendarUnit|NSWeekdayCalendarUnit fromDate:date];

     [comps setWeekday:2]; // 2: monday
     return [calendar dateFromComponents:comps];
  }


回答2:

You can use this for getting current year & month. Simply add these to previous answer as my friend had suggested.

NSInteger year = [comps year];
NSInteger month = [comps month];

Now, I think if you're getting current year & month, you can set manually for 1st date. and perform as you want.

Main thing is to get weekday .. Thanks.