swift - 使用 Date int swift 获取一年中的最后一天?

标签 swift date swift3

我想获得当年的最后一天,我需要它随时间变化,所以如果我在 2018 年使用这个函数,我得到的是 2018 年 12 月 31 日的最后一天,但如果我现在使用这个函数,它应该给出我是 2017 年 12 月 31 日。我知道我可以通过使用

var current = Date()

而且我知道我可以得到例如一年后的同一天,那应该大约是

 var dayComponents = DateComponents()
        dayComponents.day = 365
        let calendar = Calendar(identifier: .gregorian)
        if let lastDate = calendar.date(byAdding: dayComponents, to: Date()) {
            return lastDate
        } else {
            return Date()
        }

问题是我需要从现在到年底,怎么实现?

最佳答案

我会得到当前日期的当前年份部分。明年加一个。然后用它来获得那年的第一天。然后减去 1 天得到当年的最后一天。

// Get the current year
let year = Calendar.current.component(.year, from: Date())
// Get the first day of next year
if let firstOfNextYear = Calendar.current.date(from: DateComponents(year: year + 1, month: 1, day: 1)) {
    // Get the last day of the current year
    let lastOfYear = Calendar.current.date(byAdding: .day, value: -1, to: firstOfNextYear)
}

关于swift - 使用 Date int swift 获取一年中的最后一天?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44321586/

相关文章:

ios - 将 PDF 图像添加到 UIBarItem Swift

arrays - 在 SwiftUI 中更新/编辑数组元素的最佳方式

date - 如何检查 Jinja2 模板中 2 个日期之间的差异是 > 还是 < 1 个月?

ios - fetchedResultsController 返回 nil

ios - NSStreams-code 仅在调试器模式下按预期工作

ios - 当应用程序终止时,BLE 设备如何调用应用程序

swift - 如何将具有自定义指定初始化程序的 UISegmentedControl 子类化?

c# - 将结果放在表格中,除以一周中的所有天数

java - SimpleDateFormat 没有正确处理 DD

ios - 将 C 指针转换为 Swift 3