【问题标题】:Get last day of the year using Date int swift?使用 Date int swift 获取一年中的最后一天?
【发布时间】:2017-06-02 05:42:29
【问题描述】:

我想得到今年的最后一天,我需要随着时间的推移而改变,所以如果我在 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()
        }

问题是我需要从现在到年底,我该如何实现呢?

【问题讨论】:

    标签: swift date swift3


    【解决方案1】:

    我会得到当前日期的当前年份部分。加一个到明年。然后用它来获得那一年的第一天。然后减去 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)
    }
    

    【讨论】:

      【解决方案2】:

      您也可以像这样尝试获取当年的第一天加上 1 年并减去 1 天。

      var components = Calendar.current.dateComponents([.year], from: Date())
      if let startDateOfYear = Calendar.current.date(from: components) {
          components.year = 1
          components.day = -1
          let lastDateOfYear = Calendar.current.date(byAdding: components, to: startDateOfYear)
      }
      

      【讨论】:

        猜你喜欢
        • 2017-08-19
        • 2022-07-22
        • 1970-01-01
        • 2016-10-07
        • 1970-01-01
        • 1970-01-01
        • 2016-01-22
        • 2014-01-25
        相关资源
        最近更新 更多