Question

Disons que nous sommes le 15/07/2010, j'aimerais obtenir le premier jour de la semaine précédente, qui est le 5 juillet.J'ai la méthode suivante, mais cela ne fonctionne pas.Semble avoir un problème avec l'attribut de la semaine ...

+ (NSDate *)getFirstDayOfPreviousWeek
{
// Get current date
NSCalendar *cal = [[NSCalendar alloc] initWithCalendarIdentifier:NSGregorianCalendar];
NSDate *now = [NSDate date];

// Get today date at midnight
NSDateComponents *components = [cal components:( NSYearCalendarUnit | NSMonthCalendarUnit | NSDayCalendarUnit | NSHourCalendarUnit | NSMinuteCalendarUnit | NSSecondCalendarUnit | NSTimeZoneCalendarUnit) fromDate:now];
[components setHour:0];
[components setMinute:0];
[components setSecond:0];
NSInteger *dayNbr = [components weekday];
NSLog(@"week day:%@",dayNbr); // CRASH
NSDate *todayMidnight = [cal dateFromComponents:components];

// Get first day of previous week midnight
components = [[[NSDateComponents alloc] init] autorelease];
NSInteger *wd = [dayNbr intValue] * -1 + 1;
[components setWeekDay:wd];
[components setWeek:-1];
NSDate *newDate = [cal dateByAddingComponents:components toDate:todayMidnight options:0];
[cal release];

NSLog(@"new date:%@", newDate);

return newDate;
}

Pourriez-vous s'il vous plaît aider?

Merci beaucoup,

LUC

Était-ce utile?

La solution

Je pense que cela devrait être beaucoup plus facile

- (NSDate *)getFirstDayOfPreviousWeek
{
    NSCalendar *cal = [[NSCalendar alloc] initWithCalendarIdentifier:NSGregorianCalendar];
    NSDate *now = [NSDate date];
    NSLog(@"Current date: %@", now);

    // required components for today
    NSDateComponents *components = [cal components:( NSYearCalendarUnit | NSMonthCalendarUnit | NSWeekCalendarUnit | NSWeekdayCalendarUnit ) fromDate:now];

    // adjust them for first day of previous week (Monday)
    [components setWeekday:2];
    [components setWeek:([components week] - 1)];

    // construct new date and return
    NSDate *newDate = [cal dateFromComponents:components];
    NSLog(@"New date: %@", newDate);

    return newDate;
}

Note Cette solution suppose le premier jour de la semaine est lundi.

Autres conseils

Le code de terrain de jeu Swift 3 suivant montre comment obtenir le premier jour de la semaine précédente à partir de n'importe quelle date:

import Foundation

let calendar = Calendar(identifier: .gregorian)
let intialDate = Date()

// Prepare the new date components
var newDateComponents = calendar.dateComponents([.year, .month, .weekOfMonth], from: intialDate)
newDateComponents.weekOfMonth = newDateComponents.weekOfMonth! - 1 // get previous week
newDateComponents.weekday = 2 // sunday is 1, monday is 2

// Get the new date
let newDate = calendar.date(from: newDateComponents)
print(newDate ?? "Could not retrieve a date")


Si vous devez répéter cette opération, vous pouvez refroidir votre code dans une fonction ou une méthode:

import Foundation

func firstDayOfPreviousWeek(from date: Date) -> Date? {
    let calendar = Calendar(identifier: .gregorian)
    var newDateComponents = calendar.dateComponents([.year, .month, .weekOfMonth], from: date)
    newDateComponents.weekOfMonth = newDateComponents.weekOfMonth! - 1
    newDateComponents.weekday = 2
    return calendar.date(from: newDateComponents)
}


Par conséquent, le code de terrain de jeu suivant montre comment obtenir le premier jour de la semaine précédente à partir du 15 juillet 2010:

import Foundation

func firstDayOfPreviousWeek(from date: Date) -> Date? {
    let calendar = Calendar(identifier: .gregorian)
    var newDateComponents = calendar.dateComponents([.year, .month, .weekOfMonth], from: date)
    newDateComponents.weekOfMonth = newDateComponents.weekOfMonth! - 1
    newDateComponents.weekday = 2
    newDateComponents.timeZone = TimeZone(abbreviation: "GMT")
    return calendar.date(from: newDateComponents)
}

let calendar = Calendar(identifier: .gregorian)
var july15Components = DateComponents()
july15Components.day = 15
july15Components.month = 7
july15Components.year = 2010
july15Components.timeZone = TimeZone(abbreviation: "GMT")
let july15 = calendar.date(from: july15Components)!
print(july15) // prints 2010-07-15 00:00:00 +0000

let newDate = firstDayOfPreviousWeek(from: july15)
print(newDate ?? "Could not retrieve a date") // prints 2010-07-05 00:00:00 +0000

Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top