加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

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

发布时间:2020-12-14 04:29:21 所属栏目:百科 来源:网络整理
导读:我想要获得当年的拉斯日,我需要随着时间的推移而改变,所以如果我在2018年使用这个功能,我会得到2018年12月31日的最后一天,但如果我现在使用这个功能它应该给我12月31日2017年.我知道我可以通过使用获得当前日期 var current = Date() 而且我知道我可以在一年
我想要获得当年的拉斯日,我需要随着时间的推移而改变,所以如果我在2018年使用这个功能,我会得到2018年12月31日的最后一天,但如果我现在使用这个功能它应该给我12月31日2017年.我知道我可以通过使用获得当前日期

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)
}

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读