gpt4 book ai didi

swift - 使用 DateComponents 创建日期

转载 作者:行者123 更新时间:2023-11-28 11:36:48 25 4
gpt4 key购买 nike

我想得到一周的第一天和最后一天。但我的结果与苹果的文档不符: 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. 在公历中,weekday = 1 表示星期日; weekday = 2 表示星期一;等。您可以查看 calendar.maximumRange(of: .weekday) 以获得有效值的范围,您可以查看 calendar.weekdaySymbols 以了解这些 weekDay 值表示(例如“Sun”、“Mon”、“Tue”、“Wed”、“Thu”、“Fri”和“Sat”)。

  2. 你说:

    I also want to have the entire day and not 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 日开始:

    1/6/19, 12:00 AM – 1/13/19, 12:00 AM

    而在德语语言环境中,间隔从 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))

关于swift - 使用 DateComponents 创建日期,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54938512/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com