2015-09-11 15 views
5

Voglio solo un array che contenga tutti i lunedì dell'anno sotto forma di NSDate ma in modo rapido. sto usando il codice seguente nell'obiettivo -c ma non so come utilizzarlo in swift.Come ottenere tutte le domeniche in Array di data ios

NSDate *pickerDate = [NSDate date]; 
    NSLog(@"pickerDate: %@", pickerDate); 

    NSDateComponents *dateComponents; 
    NSCalendar *calendar = [NSCalendar currentCalendar]; 

    dateComponents = [calendar components:NSWeekdayCalendarUnit fromDate:pickerDate]; 
    NSInteger firstMondayOrdinal = 9 - [dateComponents weekday]; 
    dateComponents = [[NSDateComponents alloc] init]; 
    [dateComponents setDay:firstMondayOrdinal]; 
    NSDate *firstMondayDate = [calendar dateByAddingComponents:dateComponents toDate:pickerDate options:0]; 

    dateComponents = [[NSDateComponents alloc] init]; 
    [dateComponents setWeek:1]; 

    for (int i=0; i<64; i++) { 
     [dateComponents setWeek:i]; 
     NSDate *mondayDate = [calendar dateByAddingComponents:dateComponents toDate:firstMondayDate options:0]; 
     NSLog(@"week#: %i, mondayDate: %@", i, mondayDate); 
    } 
+0

Esiste una parte particolare di questo codice in cui si riscontrano problemi di traduzione? –

+0

Sì, voglio solo convertire questo codice così posso ottenere tutte le domeniche in un singolo array –

risposta

2

Qui si va,

var pickerDate = NSDate() 
println(pickerDate) 

var dateComponents: NSDateComponents? = nil 
var calendar = NSCalendar.currentCalendar() 

dateComponents = calendar.components(NSCalendarUnit.CalendarUnitWeekday, fromDate: pickerDate) 
var firstMondayOrdinal = 9 - dateComponents!.weekday 
dateComponents = NSDateComponents() 
dateComponents!.day = firstMondayOrdinal 
var firstMondayDate = calendar.dateByAddingComponents(dateComponents!, toDate: pickerDate, options: NSCalendarOptions(0)) 

dateComponents = NSDateComponents() 
dateComponents?.weekdayOrdinal = 1 

for (var i=0; i<64; i++){ 
    dateComponents?.weekdayOrdinal = i 
    var mondayDate = calendar.dateByAddingComponents(dateComponents!, toDate: firstMondayDate!, options: NSCalendarOptions.MatchFirst) 
    println("\(i)" + "\(mondayDate!)"); 
} 
+0

Grazie per aver salvato la mia giornata ... Sta funzionando perfettamente per me .... –

+2

quindi, per favore accetta la mia risposta :) (by barrando il segno di spunta visualizzato in alto a sinistra nella risposta fornita) –

1

Qui si va. È abbastanza semplice, ma ci sono alcuni trucchi, in particolare i set di opzioni per NSCalendarOptions, il fatto che dateByAddingComponents restituisce un optional, le modifiche nei nomi enum per NSCalendarUnit e il deprecazione di NSDateComponents.week, ma per il resto è semplice. Non ho controllato la logica ...

//NSDate *pickerDate = [NSDate date]; 
let pickerDate = NSDate() /* I just used today for playground */ 

//NSLog(@"pickerDate: %@", pickerDate); 
print("pickerDate: \(pickerDate)") 

//NSDateComponents *dateComponents; 
var dateComponents: NSDateComponents /* var because you keep reallocating it */ 

//NSCalendar *calendar = [NSCalendar currentCalendar]; 
let calendar = NSCalendar.currentCalendar() 

//dateComponents = [calendar components:NSWeekdayCalendarUnit fromDate:pickerDate]; 
dateComponents = calendar.components(NSCalendarUnit.Weekday, fromDate: pickerDate) 

//NSInteger firstMondayOrdinal = 9 - [dateComponents weekday]; 
let firstMondayOrdinal = 9 - dateComponents.weekday 

//dateComponents = [[NSDateComponents alloc] init]; 
dateComponents = NSDateComponents() 

//[dateComponents setDay:firstMondayOrdinal]; 
dateComponents.day = firstMondayOrdinal 

//NSDate *firstMondayDate = [calendar dateByAddingComponents:dateComponents toDate:pickerDate options:0]; 
if let firstMondayDate = calendar.dateByAddingComponents(dateComponents, toDate: pickerDate, options: NSCalendarOptions(rawValue: 0)) { 
    /* this returns an optional so test for it */ 

    //dateComponents = [[NSDateComponents alloc] init]; 
    dateComponents = NSDateComponents() 

    //[dateComponents setWeek:1]; /* week deprecated */ 
    dateComponents.weekOfYear = 1 /* this line is redundant, re-done inside for */ 

    //for (int i=0; i<64; i++) { 
    for i in 0 ..< 64 { 
     //[dateComponents setWeek:i]; 
     dateComponents.weekOfYear = i 
     // NSDate *mondayDate = [calendar dateByAddingComponents:dateComponents toDate:firstMondayDate options:0]; 
     let mondayDate = calendar.dateByAddingComponents(dateComponents, toDate: firstMondayDate, options: NSCalendarOptions(rawValue: 0)) 
     /* no need to test for nil if just printing it, but beware */ 

     //NSLog(@"week#: %i, mondayDate: %@", i, mondayDate); 
     print("week#: \(i), mondayDate: \(mondayDate)") 
    } 
} 
3

Xcode 8 • Swift 3

extension Calendar { 
    static let gregorian = Calendar(identifier: .gregorian) 
} 

extension Date { 
    var startOfWeek: Date { 
     return Calendar.gregorian.date(from: Calendar.gregorian.dateComponents([.yearForWeekOfYear, .weekOfYear], from: self))! 
    } 
    var nextSunday: Date { 
     return Calendar.gregorian.date(byAdding: DateComponents(weekOfYear: 1), to: startOfWeek)! 
    } 
} 

let firstSunday = Date().nextSunday 
var result = [firstSunday] 
(1...52).forEach { _ in 
    guard let nextSunday = result.last?.nextSunday else { return } 
    result.append(nextSunday) 
} 
print(result) // "[2017-06-11 03:00:00 +0000, 2017-06-18 03:00:00 +0000, 2017-06-25 03:00:00 +0000, 2017-07-02 03:00:00 +0000, 2017-07-09 03:00:00 +0000, 2017-07-16 03:00:00 +0000, 2017-07-23 03:00:00 +0000, 2017-07-30 03:00:00 +0000, 2017-08-06 03:00:00 +0000, 2017-08-13 03:00:00 +0000, 2017-08-20 03:00:00 +0000, 2017-08-27 03:00:00 +0000, 2017-09-03 03:00:00 +0000, 2017-09-10 03:00:00 +0000, 2017-09-17 03:00:00 +0000, 2017-09-24 03:00:00 +0000, 2017-10-01 03:00:00 +0000, 2017-10-08 03:00:00 +0000, 2017-10-15 03:00:00 +0000, 2017-10-22 03:00:00 +0000, 2017-10-29 02:00:00 +0000, 2017-11-05 02:00:00 +0000, 2017-11-12 02:00:00 +0000, 2017-11-19 02:00:00 +0000, 2017-11-26 02:00:00 +0000, 2017-12-03 02:00:00 +0000, 2017-12-10 02:00:00 +0000, 2017-12-17 02:00:00 +0000, 2017-12-24 02:00:00 +0000, 2017-12-31 02:00:00 +0000, 2018-01-07 02:00:00 +0000, 2018-01-14 02:00:00 +0000, 2018-01-21 02:00:00 +0000, 2018-01-28 02:00:00 +0000, 2018-02-04 02:00:00 +0000, 2018-02-11 02:00:00 +0000, 2018-02-18 03:00:00 +0000, 2018-02-25 03:00:00 +0000, 2018-03-04 03:00:00 +0000, 2018-03-11 03:00:00 +0000, 2018-03-18 03:00:00 +0000, 2018-03-25 03:00:00 +0000, 2018-04-01 03:00:00 +0000, 2018-04-08 03:00:00 +0000, 2018-04-15 03:00:00 +0000, 2018-04-22 03:00:00 +0000, 2018-04-29 03:00:00 +0000, 2018-05-06 03:00:00 +0000, 2018-05-13 03:00:00 +0000, 2018-05-20 03:00:00 +0000, 2018-05-27 03:00:00 +0000, 2018-06-03 03:00:00 +0000, 2018-06-10 03:00:00 +0000]\n" 
1

C'è un metodo sottovalutato ma molto comodo enumerateDates(startingAfter:matching:matchingPolicy:) di Calendar

// Create the date component matching the weekday (Sunday = 1) 
let mondayComponent = DateComponents(weekday: 2) 

// Calculate Jan 1st of the current date 
let calendar = Calendar.current 
let currentDate = Date() 
var startOfYear = currentDate 
var interval : TimeInterval = 0.0 
_ = calendar.dateInterval(of:.year, start: &startOfYear, interval: &interval, for: currentDate) 

// Get the current year as integer 
let thisYear = calendar.component(.year, from: startOfYear) 

// Create an array for the result 
var allMondays = [Date]() 

// If Jan 1st is a Monday append it to the array 
if calendar.component(.weekday, from: startOfYear) == 2 { allMondays.append(startOfYear) } 

// Now enumerate all dates matching the weekday component within this year 
// If the year reaches thisYear + 1 the block will be exited.  
calendar.enumerateDates(startingAfter: startOfYear, matching: mondayComponent, matchingPolicy: .nextTime) { (date, strict, stop) in 
    guard let date = date else { return } 
    if calendar.component(.year, from: date) > thisYear { 
     stop = true 
    } else { 
     allMondays.append(date) 
    } 
} 
Problemi correlati