swift - 在 Swift 中只用一个工作日和一个小时创建一个日期对象

标签 swift date nsdate nscalendar

我环顾四周,没有找到我需要的东西。

这是我需要的:

在 Swift 中,我想创建一个 Date(或 NSDate)对象来表示一周中的某一天以及该工作日的特定时间。我不关心年和月。

这是因为我有一个每周重复事件的系统(在特定工作日、特定时间开会,例如“每周一晚上 8 点”)。

这是我目前的代码(不起作用):

/* ################################################################## */
/**
 :returns: a Date object, with the weekday and time of the meeting.
 */
var startTimeAndDay: Date! {
    get {
        var ret: Date! = nil
        if let time = self["start_time"] {
            let timeComponents = time.components(separatedBy: ":")
            let myCalendar:Calendar = Calendar.init(identifier: Calendar.Identifier.gregorian)
            // Create our answer from the components of the result.
            let myComponents: DateComponents = DateComponents(calendar: myCalendar, timeZone: nil, era: nil, year: nil, month: nil, day: nil, hour: Int(timeComponents[0])!, minute: Int(timeComponents[1])!, second: nil, nanosecond: nil, weekday: self.weekdayIndex, weekdayOrdinal: nil, quarter: nil, weekOfMonth: nil, weekOfYear: nil, yearForWeekOfYear: nil)
            ret = myCalendar.date(from: myComponents)
        }

        return ret
    }
}

有很多方法可以将日期解析成这个,但我想创建一个 Date 对象以便稍后解析。

如有任何帮助,我们将不胜感激。

最佳答案

(NS)Date 表示绝对时间点,对工作日、小时、日历、时区等一无所知。在内部表示 作为自“引用日期”2001 年 1 月 1 日(格林威治标准时间)以来的秒数。

如果你正在使用 EventKit 那么 EKRecurrenceRule可能 更适合。它是一个用于描述重复事件的重复模式的类。

或者,将事件存储为 DateComponentsValue,并且 必要时计算具体的Date

示例:每周一晚上 8 点开会:

let meetingEvent = DateComponents(hour: 20, weekday: 2)

下次 session 是什么时候?

let now = Date()
let cal = Calendar.current
if let nextMeeting = cal.nextDate(after: now, matching: meetingEvent, matchingPolicy: .strict) {
    print("now:", DateFormatter.localizedString(from: now, dateStyle: .short, timeStyle: .short))
    print("next meeting:", DateFormatter.localizedString(from: nextMeeting, dateStyle: .short, timeStyle: .short))
}

输出:

now: 21.11.16, 20:20
next meeting: 28.11.16, 20:00

关于swift - 在 Swift 中只用一个工作日和一个小时创建一个日期对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40727102/

相关文章:

ios - 从 UICollectionView 到 UILabel 的 myLabel 导出无效。 socket 无法连接到重复内容

ios - Swift - UIViewController 内的扩展 UIView

javascript - 如何计算两个日期之间经过的 "quarters"的数量,其中季度不仅仅是一年中的一个季度,而是特定日期?

Javascript/两天之间的 Angular 天数(含)

javascript - 日期对象值发生变化 - JavaScript

ios - 从不是 View Controller 的类导航到 View Controller

xcode - 在 Swift 中以编程方式切换标签栏

ios - 来自 NSTimeZone 的时区城市的完整列表

iphone - 我必须在下面的代码中释放 NSDate 吗?

ios - 如何在 Swift 中使用 UIDatePicker 仅在没有日期组件的情况下将时间存储在 CoreData 中?