如何在swift中获得本周的本周日期

时间:2015-10-28 16:59:29

标签: swift date nscalendar

我试图获得本周的星期一。这在我的表格视图中被视为一周的第一天。 我还需要获得本周的周日。在我的表格视图中,这被视为一周的最后一天。

目前的尝试:

>>> import csv
>>> with open('test.txt') as csvfile:
...     reader = csv.DictReader(csvfile, delimiter='\t')
...     for row in reader:
...     # append your lists
...         print(row['ID'], row['Gender'])

8 个答案:

答案 0 :(得分:44)

我写了日期扩展来获取特定工作日的日期,这里使用Swift 4是多么容易,

Date.today().next(.monday)                    // Feb 12, 2018 at 12:00 AM
Date.today().next(.sunday)                    //  Feb 11, 2018 at 12:00 AM


Date.today().previous(.sunday)                // Feb 4, 2018 at 12:00 AM
Date.today().previous(.monday)                // Feb 5, 2018 at 12:00 AM

Date.today().previous(.thursday)              // Feb 1, 2018 at 12:00 AM
Date.today().next(.thursday)                  // Feb 15, 2018 at 12:00 AM
Date.today().previous(.thursday,
                      considerToday: true)    // Feb 8, 2018 at 11:04 PM


Date.today().next(.monday)
            .next(.sunday)
            .next(.thursday)                  // Feb 22, 2018 at 12:00 AM

这是日期扩展名,

extension Date {

  static func today() -> Date {
      return Date()
  }

  func next(_ weekday: Weekday, considerToday: Bool = false) -> Date {
    return get(.Next,
               weekday,
               considerToday: considerToday)
  }

  func previous(_ weekday: Weekday, considerToday: Bool = false) -> Date {
    return get(.Previous,
               weekday,
               considerToday: considerToday)
  }

  func get(_ direction: SearchDirection,
           _ weekDay: Weekday,
           considerToday consider: Bool = false) -> Date {

    let dayName = weekDay.rawValue

    let weekdaysName = getWeekDaysInEnglish().map { $0.lowercased() }

    assert(weekdaysName.contains(dayName), "weekday symbol should be in form \(weekdaysName)")

    let searchWeekdayIndex = weekdaysName.index(of: dayName)! + 1

    let calendar = Calendar(identifier: .gregorian)

    if consider && calendar.component(.weekday, from: self) == searchWeekdayIndex {
      return self
    }

    var nextDateComponent = DateComponents()
    nextDateComponent.weekday = searchWeekdayIndex


    let date = calendar.nextDate(after: self,
                                 matching: nextDateComponent,
                                 matchingPolicy: .nextTime,
                                 direction: direction.calendarSearchDirection)

    return date!
  }

}

// MARK: Helper methods
extension Date {
  func getWeekDaysInEnglish() -> [String] {
    var calendar = Calendar(identifier: .gregorian)
    calendar.locale = Locale(identifier: "en_US_POSIX")
    return calendar.weekdaySymbols
  }

  enum Weekday: String {
    case monday, tuesday, wednesday, thursday, friday, saturday, sunday
  }

  enum SearchDirection {
    case Next
    case Previous

    var calendarSearchDirection: Calendar.SearchDirection {
      switch self {
      case .Next:
        return .forward
      case .Previous:
        return .backward
      }
    }
  }
}

答案 1 :(得分:24)

您可以使用第一个工作日为星期一的日历ISO8601:

Swift 3或更高版本

var mondaysDate: Date {
    return Calendar(identifier: .iso8601).date(from: Calendar(identifier: .iso8601).dateComponents([.yearForWeekOfYear, .weekOfYear], from: Date()))!
}

print(mondaysDate.description(with: .current))   // Monday, July 16, 2018 at 12:00:00 AM Brasilia Standard Time"

作为扩展名:

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

extension Date {
    var currentWeekMonday: Date {
        return Calendar.iso8601.date(from: Calendar.iso8601.dateComponents([.yearForWeekOfYear, .weekOfYear], from: self))!
    }
}
let currentWeekMonday = Date().currentWeekMonday
print(currentWeekMonday.description(with: .current)) // Monday, July 16, 2018 at 12:00:00 AM Brasilia Standard Time 

答案 2 :(得分:8)

这是我创建的扩展程序,首先它会找到星期日,然后再添加一天

if someExpression then onePossibility else otherPossibility

答案 3 :(得分:6)

这是Sandeep's answer的简化版。

用法:

Date().next(.monday)
Date().next(.monday, considerToday: true)
Date().next(.monday, direction: .backward)

扩展:

public func next(_ weekday: Weekday,
                 direction: Calendar.SearchDirection = .forward,
                 considerToday: Bool = false) -> Date
{
    let calendar = Calendar(identifier: .gregorian)
    let components = DateComponents(weekday: weekday.rawValue)

    if considerToday &&
        calendar.component(.weekday, from: self) == weekday.rawValue
    {
        return self
    }

    return calendar.nextDate(after: self,
                             matching: components,
                             matchingPolicy: .nextTime,
                             direction: direction)!
}

public enum Weekday: Int {
    case sunday = 1, monday, tuesday, wednesday, thursday, friday, saturday
}

答案 4 :(得分:3)

尝试使用:

calendar.firstWeekday = 2

修改

更具体地说:NSCalendar.currentCalendar()返回用户日历。根据文件:

  

返回的日历由当前用户所选系统区域设置的设置构成,并覆盖用户在“系统偏好设置”中指定的任何自定义设置。

如果您希望星期一作为第一天,我认为您应该使用:

let calendar = NSCalendar(calendarIdentifier: NSCalendarIdentifierGregorian)!
calendar!.firstWeekday = 2

答案 5 :(得分:0)

加入@Saneep回答

如果您希望根据给定/当前日期获得确切的日期时间(假设您想要将星期一&dates. {date} - &gt; 23-05-2016 12:00:00转换为23-05-2016 05:35:17),请尝试以下操作:< / p>

func convertDate(date: NSDate, toGivendate: NSDate) -> NSDate {
    let calendar = NSCalendar.currentCalendar()
    let comp = calendar.components([.Year, .Month, .Day, .Hour, .Minute, .Second], fromDate: toGivendate)
    let hour = comp.hour
    let minute = comp.minute
    let second = comp.second

    let dateComp = calendar.components([.Year, .Month, .Day], fromDate: date)
    let year = dateComp.year
    let month = dateComp.month
    let day = dateComp.day

    let components = NSDateComponents()
    components.year = year
    components.month = month
    components.day = day
    components.hour = hour
    components.minute = minute
    components.second = second

    let newConvertedDate = calendar.dateFromComponents(components)

    return newConvertedDate!
}

答案 6 :(得分:0)

Swift 4解决方案

我已经根据自己的要求弄清楚了,在那里我找到了后续的日期。

1. Today

2. Tomorrow 

3. This Week 

4. This Weekend 

5. Next Week 

6. Next Weekend

因此,我创建了Date Extension来获取当前周下周的日期。

代码

extension Date {

    func getWeekDates() -> (thisWeek:[Date],nextWeek:[Date]) {
        var tuple: (thisWeek:[Date],nextWeek:[Date])
        var arrThisWeek: [Date] = []
        for i in 0..<7 {
            arrThisWeek.append(Calendar.current.date(byAdding: .day, value: i, to: startOfWeek)!)
        }
        var arrNextWeek: [Date] = []
        for i in 1...7 {
            arrNextWeek.append(Calendar.current.date(byAdding: .day, value: i, to: arrThisWeek.last!)!)
        }
        tuple = (thisWeek: arrThisWeek,nextWeek: arrNextWeek)
        return tuple
    }

    var tomorrow: Date {
        return Calendar.current.date(byAdding: .day, value: 1, to: noon)!
    }
    var noon: Date {
        return Calendar.current.date(bySettingHour: 12, minute: 0, second: 0, of: self)!
    }

    var startOfWeek: Date {
        let gregorian = Calendar(identifier: .gregorian)
        let sunday = gregorian.date(from: gregorian.dateComponents([.yearForWeekOfYear, .weekOfYear], from: self))
        return gregorian.date(byAdding: .day, value: 1, to: sunday!)!
    }

    func toDate(format: String) -> String {
        let formatter = DateFormatter()
        formatter.dateFormat = format
        return formatter.string(from: self)
    }
}

用法:

let arrWeekDates = Date().getWeekDates() // Get dates of Current and Next week.
let dateFormat = "MMM dd" // Date format
let thisMon = arrWeekDates.thisWeek.first!.toDate(format: dateFormat)
let thisSat = arrWeekDates.thisWeek[arrWeekDates.thisWeek.count - 2].toDate(format: dateFormat)
let thisSun = arrWeekDates.thisWeek[arrWeekDates.thisWeek.count - 1].toDate(format: dateFormat)

let nextMon = arrWeekDates.nextWeek.first!.toDate(format: dateFormat)
let nextSat = arrWeekDates.nextWeek[arrWeekDates.nextWeek.count - 2].toDate(format: dateFormat)
let nextSun = arrWeekDates.nextWeek[arrWeekDates.nextWeek.count - 1].toDate(format: dateFormat)

print("Today: \(Date().toDate(format: dateFormat))") // Sep 26
print("Tomorrow: \(Date().tomorrow.toDate(format: dateFormat))") // Sep 27
print("This Week: \(thisMon) - \(thisSun)") // Sep 24 - Sep 30
print("This Weekend: \(thisSat) - \(thisSun)") // Sep 29 - Sep 30
print("Next Week: \(nextMon) - \(nextSun)") // Oct 01 - Oct 07
print("Next Weekend: \(nextSat) - \(nextSun)") // Oct 06 - Oct 07

您可以根据需要修改Extension

谢谢!

答案 7 :(得分:0)

简单代码(请记住要更好地处理可选内容):

let now = Date()

var calendar = Calendar(identifier: .gregorian)

let timeZone = TimeZone(identifier: "UTC")!

let desiredWeekDay = 2

let weekDay = calendar.component(.weekday, from: now)
var weekDayDate = calendar.date(bySetting: .weekday, value: desiredWeekDay, of: now)!

/// Swift will give back the closest day matching the value above so we need to manipulate it to be always included at cuurent week.
if weekDayDate > now, weekDay > desiredWeekDay {
    weekDayDate = weekDayDate - 7*24*60*60
}

print(weekDayDate)