Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to calculate first NSDate of current week?

i.e.:

  NSDate *firstDayOfWeek = [[NSDate date] firstDayOfWeek];

for example, today is Aug 19, I'd want to get a NSDate of 2010-08-15 12:00am from above line of code. Thanks!

like image 219
ohho Avatar asked Aug 19 '10 06:08

ohho


People also ask

How do I display current week in HTML?

HTML input type="week"

How do you get the current week start date and end date in typescript?

You can also use following lines of code to get first and last date of the week: var curr = new Date; var firstday = new Date(curr. setDate(curr. getDate() - curr.


1 Answers

I think this threads responds to what you're looking for: http://www.cocoabuilder.com/archive/cocoa/211648-nsdatecomponents-question.html#211826

Note however that it doesn't handle Mondays as first days of the week, so you may have to tweek it a little by substracting [gregorian firstWeekday] instead of just 1. Also, I modified it to use -currentCalendar, but it's up to you :-)

NSDate *today = [NSDate date];
NSCalendar *gregorian = [NSCalendar currentCalendar];

// Get the weekday component of the current date
NSDateComponents *weekdayComponents = [gregorian components:NSWeekdayCalendarUnit fromDate:today];
/*
Create a date components to represent the number of days to subtract
from the current date.
The weekday value for Sunday in the Gregorian calendar is 1, so
subtract 1 from the number
of days to subtract from the date in question.  (If today's Sunday,
subtract 0 days.)
*/
NSDateComponents *componentsToSubtract = [[NSDateComponents alloc] init];
/* Substract [gregorian firstWeekday] to handle first day of the week being something else than Sunday */
[componentsToSubtract setDay: - ([weekdayComponents weekday] - [gregorian firstWeekday])];
NSDate *beginningOfWeek = [gregorian dateByAddingComponents:componentsToSubtract toDate:today options:0];

/*
Optional step:
beginningOfWeek now has the same hour, minute, and second as the
original date (today).
To normalize to midnight, extract the year, month, and day components
and create a new date from those components.
*/
NSDateComponents *components = [gregorian components: (NSYearCalendarUnit | NSMonthCalendarUnit | NSDayCalendarUnit)
                                            fromDate: beginningOfWeek];
beginningOfWeek = [gregorian dateFromComponents: components];
like image 125
Thibault Martin-Lagardette Avatar answered Sep 23 '22 17:09

Thibault Martin-Lagardette