ios objective-c cocoa-touch nsdate

ios - Fecha de inicio y finalización de la semana actual



objective-c cocoa-touch (13)

Una versión Swift

de la answer de vikingosegundo :

let calendar = NSCalendar.currentCalendar() var startOfTheWeek: NSDate? var endOfWeek: NSDate! var interval = NSTimeInterval(0) calendar.rangeOfUnit(.WeekOfMonth, startDate: &startOfTheWeek, interval: &interval, forDate: NSDate()) endOfWeek = startOfTheWeek!.dateByAddingTimeInterval(interval - 1)

Quiero obtener la fecha de inicio y finalización de la semana actual y también quiero usar la fecha de inicio y finalización de la semana anterior y la próxima semana de la fecha de inicio y finalización en el mes actual.

Gracias por adelantado.


Aprovechando el método rangeOfUnit:startDate:interval:forDate: de NSDate , hay una manera más simple de lograr esto:

- (void)startDate:(NSDate **)start andEndDate:(NSDate **)end ofWeekOn:(NSDate *)date{ NSDate *startDate = nil; NSTimeInterval duration = 0; BOOL b = [[NSCalendar currentCalendar] rangeOfUnit:NSWeekCalendarUnit startDate:&startDate interval:&duration forDate:date]; if(! b){ *start = nil; *end = nil; return; } NSDate *endDate = [startDate dateByAddingTimeInterval:duration-1]; *start = startDate; *end = endDate; } NSDate *this_start = nil, *this_end = nil; [self startDate:&this_start andEndDate:&this_end ofWeekOn:[NSDate date]];

Entonces ahora tiene la fecha de inicio y la de finalización de esta semana. Entonces la semana pasada:

NSDate *lastWeekDate = [this_start dateByAddingTimeInterval:-10]; NSDate *last_start = nil, *last_end = nil; [self startDate:&last_start andEndDate:&last_end ofWeekOn:lastWeekDate];

La próxima semana:

NSDate *nextWeekDate = [this_end dateByAddingTimeInterval:10]; NSDate *next_start = nil, *next_end = nil; [self startDate:&next_start andEndDate:&next_end ofWeekOn:nextWeekDate];

Ahora los tienes todos.


Aquí está la versión de Swift 3: -

extension Date { var startOfWeek: Date? { let gregorian = Calendar(identifier: .gregorian) guard let sunday = gregorian.date(from: gregorian.dateComponents([.yearForWeekOfYear, .weekOfYear], from: self)) else { return nil } return gregorian.date(byAdding: .day, value: 1, to: sunday) } var endOfWeek: Date? { let gregorian = Calendar(identifier: .gregorian) guard let sunday = gregorian.date(from: gregorian.dateComponents([.yearForWeekOfYear, .weekOfYear], from: self)) else { return nil } return gregorian.date(byAdding: .day, value: 7, to: sunday) } }

Puede obtener la fecha de inicio de la semana y la fecha de finalización así:

let startWeek = Date().startOfWeek let endWeek = Date().endOfWeek print(startWeek ?? "not found start date") print(endWeek ?? "not found end date")


Aquí hay un código y también verifica un caso límite en el que el comienzo de la semana comienza el mes anterior. Puede obtener el final de semana estableciendo setWeekday en 7 y puede obtener la semana anterior restando 1 de [components week]

// Finds the date for the first day of the week - (NSDate *)getFirstDayOfTheWeekFromDate:(NSDate *)givenDate { NSCalendar *calendar = [NSCalendar currentCalendar]; // Edge case where beginning of week starts in the prior month NSDateComponents *edgeCase = [[NSDateComponents alloc] init]; [edgeCase setMonth:2]; [edgeCase setDay:1]; [edgeCase setYear:2013]; NSDate *edgeCaseDate = [calendar dateFromComponents:edgeCase]; NSDateComponents *components = [calendar components:NSYearCalendarUnit|NSMonthCalendarUnit|NSWeekCalendarUnit|NSWeekdayCalendarUnit fromDate:edgeCaseDate]; [components setWeekday:1]; // 1 == Sunday, 7 == Saturday [components setWeek:[components week]]; NSLog(@"Edge case date is %@ and beginning of that week is %@", edgeCaseDate , [calendar dateFromComponents:components]); // Find Sunday for the given date components = [calendar components:NSYearCalendarUnit|NSMonthCalendarUnit|NSWeekCalendarUnit|NSWeekdayCalendarUnit fromDate:givenDate]; [components setWeekday:1]; // 1 == Sunday, 7 == Saturday [components setWeek:[components week]]; NSLog(@"Original date is %@ and beginning of week is %@", givenDate , [calendar dateFromComponents:components]); return [calendar dateFromComponents:components]; }


Aquí hay una solución para swift4, podemos obtener todos los días de la semana actual.

var calendar = Calendar(identifier: Calendar.Identifier.gregorian) let today = calendar.startOfDay(for: Date()) let dayOfWeek = calendar.component(.weekday, from: today) - calendar.firstWeekday let weekdays = calendar.range(of: .weekday, in: .weekOfYear, for: today)! let days = (weekdays.lowerBound ..< weekdays.upperBound) .flatMap { calendar.date(byAdding: .day, value: $0 - dayOfWeek, to: today) }


En veloz 3.0

let cal = NSCalendar.current //weekday let weekday = cal.component(.weekday, from: Date()) var dateComp = cal.dateComponents([.hour, .minute, .second, .day, .month, .year], from: Date()) print(dateComp.day!) //Start Date of the week - Sunday dateComp.day = dateComp.day! - (weekday - 1)// start date of week print(cal.date(from: dateComp)!) //End Date of the Week - Saturday dateComp = cal.dateComponents([.hour, .minute, .second, .day, .month, .year], from: Date()) dateComp.day = dateComp.day! + (7 - weekday) print(cal.date(from: dateComp)!)


Esta es una manera elegante para Swift 3 (Xcode 8+):

extension Date { var startOfWeek: Date { let date = Calendar.current.date(from: Calendar.current.dateComponents([.yearForWeekOfYear, .weekOfYear], from: self))! let dslTimeOffset = NSTimeZone.local.daylightSavingTimeOffset(for: date) return date.addingTimeInterval(dslTimeOffset) } var endOfWeek: Date { return Calendar.current.date(byAdding: .second, value: 604799, to: self.startOfWeek)! } }

Y podemos usar esta extensión de esta manera:

print(Date().startOfWeek) print(Date().endOfWeek)


Primero encuentra la fecha actual ...

NSDate *today = [NSDate date]; NSCalendar *gregorian = [[NSCalendar alloc] initWithCalendarIdentifier:NSGregorianCalendar]; NSDateComponents *weekdayComponents = [gregorian components:NSWeekdayCalendarUnit | NSHourCalendarUnit | NSMinuteCalendarUnit | NSSecondCalendarUnit fromDate:today];

Calcule el número de días para substraerse a partir de hoy, para obtener el primer día de la semana. En este caso, el primer día de la semana es el lunes. Esto se representa restando primero 0 con el entero del día de la semana seguido de agregar 2 al setDay.

Domingo = 1, lunes = 2, martes = 3, miércoles = 4, jueves = 5, viernes = 6 y sábado = 7. Al agregar más a este número entero, pasará a la semana siguiente.

NSDateComponents *componentsToSubtract = [[NSDateComponents alloc] init]; [componentsToSubtract setDay: (0 - [weekdayComponents weekday]) + 2]; [componentsToSubtract setHour: 0 - [weekdayComponents hour]]; [componentsToSubtract setMinute: 0 - [weekdayComponents minute]]; [componentsToSubtract setSecond: 0 - [weekdayComponents second]];

Crear fecha para el primer día de la semana

NSDate *beginningOfWeek = [gregorian dateByAddingComponents:componentsToSubtract toDate:today options:0];

Al agregar 6 a la fecha del primer día, podemos obtener el último día, en nuestro ejemplo del domingo.

NSDateComponents *componentsToAdd = [gregorian components:NSDayCalendarUnit fromDate:beginningOfWeek]; [componentsToAdd setDay:6]; NSDate *endOfWeek = [gregorian dateByAddingComponents:componentsToAdd toDate:beginningOfWeek options:0];

para el próximo y el anterior ...

-(IBAction)Week_CalendarActionEvents:(id)sender{ NSCalendar *gregorian = [[[NSCalendar alloc] initWithCalendarIdentifier:NSGregorianCalendar] autorelease]; NSDateComponents *offsetComponents = [[[NSDateComponents alloc] init] autorelease]; NSDate *nextDate; if(sender==Week_prevBarBtn) // Previous button events [offsetComponents setDay:-7]; else if(sender==Week_nextBarBtn) // next button events [offsetComponents setDay:7]; nextDate = [gregorian dateByAddingComponents:offsetComponents toDate:selectedDate options:0]; selectedDate = nextDate; [selectedDate retain]; NSDateComponents *components = [gregorian components:NSWeekCalendarUnit fromDate:selectedDate]; NSInteger week = [components week]; NSDateFormatter *formatter = [[NSDateFormatter alloc] init]; [formatter setDateFormat:@"MMMM YYYY"]; NSString *stringFromDate = [formatter stringFromDate:selectedDate]; [formatter release]; [Week_weekBarBtn setTitle:[NSString stringWithFormat:@"%@,Week %d",stringFromDate,week]]; }


Puede obtener el día y la fecha actuales con el siguiente código:

NSDate *today = [NSDate date]; NSDateFormatter *dateFormat = [[[NSDateFormatter alloc] init] autorelease]; [dateFormat setDateFormat:@"EEEE"]; NSString *weekDay = [dateFormat stringFromDate:today]; [dateFormat setDateFormat:@"dd"]; NSString *thedate=[dateFormat stringFromDate:today]; //[dateFormat release]; NSLog(@"%@ %@", weekDay,thedate);

Ahora, debe poner algo de lógica para calcular la fecha de inicio y la fecha de finalización de la semana. La lógica será de ese tipo,

si el día de la semana es el lunes

entonces

fecha de inicio = fecha actual - 0

fecha de finalización = fecha actual + 6

y así

Creo que puedes entenderlo.


Resuelvo el problema gracias por el apoyo

Código: da la fecha de inicio y finalización de la semana actual.

NSDate *today = [NSDate date]; NSLog(@"Today date is %@",today); dateFormat = [[NSDateFormatter alloc] init]; [dateFormat setDateFormat:@"yyyy-MM-dd"];// you can use your format. //Week Start Date NSCalendar *gregorian = [[NSCalendar alloc] initWithCalendarIdentifier:NSGregorianCalendar]; NSDateComponents *components = [gregorian components:NSWeekdayCalendarUnit | NSYearCalendarUnit | NSMonthCalendarUnit | NSDayCalendarUnit fromDate:today]; int dayofweek = [[[NSCalendar currentCalendar] components:NSWeekdayCalendarUnit fromDate:today] weekday];// this will give you current day of week [components setDay:([components day] - ((dayofweek) - 2))];// for beginning of the week. NSDate *beginningOfWeek = [gregorian dateFromComponents:components]; NSDateFormatter *dateFormat_first = [[NSDateFormatter alloc] init]; [dateFormat_first setDateFormat:@"yyyy-MM-dd"]; dateString2Prev = [dateFormat stringFromDate:beginningOfWeek]; weekstartPrev = [[dateFormat_first dateFromString:dateString2Prev] retain]; NSLog(@"%@",weekstartPrev); //Week End Date NSCalendar *gregorianEnd = [[NSCalendar alloc] initWithCalendarIdentifier:NSGregorianCalendar]; NSDateComponents *componentsEnd = [gregorianEnd components:NSWeekdayCalendarUnit | NSYearCalendarUnit | NSMonthCalendarUnit | NSDayCalendarUnit fromDate:today]; int Enddayofweek = [[[NSCalendar currentCalendar] components:NSWeekdayCalendarUnit fromDate:today] weekday];// this will give you current day of week [componentsEnd setDay:([componentsEnd day]+(7-Enddayofweek)+1)];// for end day of the week NSDate *EndOfWeek = [gregorianEnd dateFromComponents:componentsEnd]; NSDateFormatter *dateFormat_End = [[NSDateFormatter alloc] init]; [dateFormat_End setDateFormat:@"yyyy-MM-dd"]; dateEndPrev = [dateFormat stringFromDate:EndOfWeek]; weekEndPrev = [[dateFormat_End dateFromString:dateEndPrev] retain]; NSLog(@"%@",weekEndPrev);


rangeOfUnit:startDate:interval:forDate: Le da el inicio y el intervalo para una determinada unidad de tiempo. Con él es fácil encontrar el comienzo de la semana en el calendario usado y agregar el rango-1 para obtener el último segundo en esa semana.

NSCalendar *cal = [NSCalendar currentCalendar]; NSDate *now = [NSDate date]; NSDate *startOfTheWeek; NSDate *endOfWeek; NSTimeInterval interval; [cal rangeOfUnit:NSWeekCalendarUnit startDate:&startOfTheWeek interval:&interval forDate:now]; //startOfWeek holds now the first day of the week, according to locale (monday vs. sunday) endOfWeek = [startOfTheWeek dateByAddingTimeInterval:interval-1]; // holds 23:59:59 of last day in week.


Swift 3

Primero encuentra la fecha actual ...

let today = Date() let gregorian = Calendar(identifier: .gregorian) var weekdayComponents: DateComponents? = gregorian.dateComponents([.weekday], from: today)

Domingo = 1, lunes = 2, martes = 3, miércoles = 4, jueves = 5, viernes = 6 y sábado = 7.

var componentsToSubtract = DateComponents() componentsToSubtract.day = (0 - (weekdayComponents?.weekday!)!) + 2 beginningOfWeek = gregorian.date(byAdding: componentsToSubtract, to: today) var componentsToAdd: DateComponents? = gregorian.dateComponents([.day], from: beginningOfWeek!) componentsToAdd?.day = 6 endOfWeek = gregorian.date(byAdding: componentsToAdd!, to: beginningOfWeek!) let components: DateComponents? = gregorian.dateComponents([.month], from: beginningOfWeek!) let month: Int? = components?.month let components1: DateComponents? = gregorian.dateComponents([.month], from: endOfWeek!) let month1: Int? = components1?.month print("/(month) - /(month1)") showDate(start:beginningOfWeek!, end:endOfWeek!, strtMn:month!, endMn:month1!) func showDate(start:Date, end:Date, strtMn:Int, endMn:Int) { if strtMn == endMn{ let formatter = DateFormatter() formatter.dateFormat = "MMM dd" let stringFromDate: String = formatter.string(from: start) let formatter1 = DateFormatter() formatter1.dateFormat = "dd" let stringFromDate1: String = formatter1.string(from: end) print("/(stringFromDate) - /(stringFromDate1)") lblDate.text = "/(stringFromDate) - /(stringFromDate1)" } else{ let formatter = DateFormatter() formatter.dateFormat = "MMM dd" let stringFromDate: String = formatter.string(from: start) let formatter1 = DateFormatter() formatter1.dateFormat = "MMM dd" let stringFromDate1: String = formatter1.string(from: end) print("/(stringFromDate) - /(stringFromDate1)") lblDate.text = "/(stringFromDate) - /(stringFromDate1)" } }

para el próximo y el anterior ...

@IBAction func week_CalendarActionEvents(_ sender: UIButton) { let gregorian = Calendar(identifier: .gregorian) var offsetComponents = DateComponents() var nextStrtDate: Date? var nextEndDate: Date? var startDate: Date? var endDate: Date? startDate = beginningOfWeek endDate = endOfWeek if sender.tag == 1 { offsetComponents.day = -7 } else if sender.tag == 2 { offsetComponents.day = 7 } nextStrtDate = gregorian.date(byAdding: offsetComponents, to:startDate!) startDate = nextStrtDate beginningOfWeek = startDate nextEndDate = gregorian.date(byAdding: offsetComponents, to: endDate!) endDate = nextEndDate endOfWeek = endDate let components: DateComponents? = gregorian.dateComponents([.month], from: startDate!) let month: Int? = components?.month let components1: DateComponents? = gregorian.dateComponents([.month], from: endDate!) let month1: Int? = components1?.month print("/(month)- /(month1)") showDate(start:startDate!, end:endDate!, strtMn:month!, endMn:month1!) }


//Begining of Week Date - (NSDate*) beginingOfWeekOfDate{ NSCalendar *tmpCalendar = [NSCalendar currentCalendar]; NSDateComponents *components = [tmpCalendar components:NSCalendarUnitYear|NSCalendarUnitMonth|NSCalendarUnitWeekOfYear|NSCalendarUnitWeekday fromDate:self];//get the required calendar units NSInteger weekday = tmpCalendar.firstWeekday; components.weekday = weekday; //weekday components.hour = 0; components.minute = 0; components.second = 0; NSDate *fireDate = [tmpCalendar dateFromComponents:components]; return fireDate; } //End of Week Date -(NSDate *)endOfWeekFromDate{ NSCalendar *tmpCalendar = [NSCalendar currentCalendar]; NSDateComponents *components = [tmpCalendar components:NSCalendarUnitYear|NSCalendarUnitMonth|NSCalendarUnitWeekOfYear|NSCalendarUnitWeekday fromDate:self];//get the required calendar units int weekday = 7; //Saturday if (tmpCalendar.firstWeekday != 1) { weekday = 1; } components.weekday = weekday;//weekday components.hour = 23; components.minute = 59; components.second = 59; NSDate *fireDate = [tmpCalendar dateFromComponents:components]; return fireDate; }