使用DateComponents创建日期

时间:2019-03-01 05:35:16

标签: swift calendar nsdatecomponents

我想获取一周的第一天和最后一天。但是我的结果与苹果的文档不符: https://developer.apple.com/documentation/foundation/nsdatecomponents/1410442-weekday

这是我的功能:

func startAndEndDateOfWeek(weekOfYearWithYear: (week: Int,year: Int)) -> (start: Date, end: Date) {
    var output = (start: Date.init(), end: Date.init())

    let calendar = Calendar(identifier: .gregorian)
    var firstDayComponents = DateComponents()
    firstDayComponents.weekOfYear = weekOfYearWithYear.week
    firstDayComponents.yearForWeekOfYear = weekOfYearWithYear.year
    firstDayComponents.weekday = 1

    let firstDay = calendar.date(from: firstDayComponents)

    var lastDayComponents = DateComponents()
    lastDayComponents.weekOfYear = weekOfYearWithYear.week
    lastDayComponents.yearForWeekOfYear = weekOfYearWithYear.year
    lastDayComponents.weekday = 2

    let lastDay = calendar.date(from: lastDayComponents)
    output = (start: firstDay!, end: lastDay!)
    return output
}

.weekday = 2->导致星期日,而不是0。

enter image description here

我也希望整天而不是16:00。

1 个答案:

答案 0 :(得分:2)

一些观察结果:

  1. 在公历中,工作日= 1表示星期日;工作日= 2表示星期一;等等。您可以查看calendar.maximumRange(of: .weekday)以获取有效值的范围,也可以查看calendar.weekdaySymbols以查看这些weekDay值的含义(例如,“ Sun”,“ Mon”, “星期二”,“星期三”,“星期四”,“星期五”和“星期六”)。

  2. 您说的是

      

    我也希望整天而不是16:00。

    Date对象引用了某个时刻。因此,它不能代表“整个一天”。但这可以代表午夜(在您所在时区的午夜可能在格林尼治标准时间(GMT)/ UTC /祖鲁(Zulu)下午4点。

    您也可以返回DateInterval,它代表一个时间范围。

    func interval(ofWeek week: Int, in year: Int) -> DateInterval {
        let calendar = Calendar.current
    
        let date = DateComponents(calendar: calendar, weekOfYear: week, yearForWeekOfYear: year).date!
        return calendar.dateInterval(of: .weekOfYear, for: date)!
    }
    

    然后

    let formatter = DateIntervalFormatter()
    formatter.dateStyle = .short
    formatter.timeStyle = .short
    
    let year = Calendar.current.component(.year, from: Date())
    let dateInterval = interval(ofWeek: 2, in: year)
    print(formatter.string(from: dateInterval))
    

    在美国语言环境中,间隔时间为1月6日:

      

    19/1/6上午12:002:00– 1/13/19上午12:00

    在德国语言环境中,间隔从7日开始:

      

    07.01.19,00:00 – 14.01.19,00:00

  3. 如果您要从一周的第一天开始和一周的最后一天开始,可以执行以下操作:

    func startAndEndDate(ofWeek week: Int, in year: Int) -> (Date, Date) {
        let date = DateComponents(calendar: calendar, weekOfYear: week, yearForWeekOfYear: year).date!
        let lastDate = calendar.date(byAdding: .day, value: 6, to: date)!
    
        return (date, lastDate)
    }
    

    然后

    let formatter = DateFormatter()
    formatter.dateStyle = .short
    
    let year = Calendar.current.component(.year, from: Date())
    let (start, end) = startAndEndDate(ofWeek: 2, in: year)
    print(formatter.string(from: start), "-", formatter.string(from: end))