【问题标题】:How can i print the dates of the first five month of a given year in the format below [closed]如何以以下格式打印给定年份的前五个月的日期[关闭]
【发布时间】:2019-12-28 11:27:36
【问题描述】:

我想使用以下格式打印给定年份的前 5 个月的日期。

2019-05, 2019-04, 2019-03, 2019-02, 2019-01

我使用for循环来实现这个

    var  first5monthIn2019 : [String]{
    var dates : [String] = []
    for i in 01...05 {
        dates.append("2019-0\(i)")
    }
      return dates
    }

是否有任何公认的方法使用NSdate 来实现上述目标。

【问题讨论】:

  • 你到底想问什么说你想要一年的前 5 个月,并且在你的方法中你编码得到一个月的 5 天?
  • @Abhishek 而不是贬低我的问题,如果您提出修改建议会很有帮助
  • NSDateComponents 怎么样?
  • @Willeke NSDateComponents ?这是如何实现的?
  • 首先我没有否决你的问题,当然我想帮忙,但问题是我无法理解你是要求一个月的前 5 天还是第一个一年中的 5 个月。

标签: swift date nsdate nsdateformatter nsdatecomponents


【解决方案1】:

这是一个使用 DateComponents 的简单解决方案

for month in 1...5 {
    if let date = DateComponents(calendar: Calendar.current, year: 2019, month: month, day: 1).date {
        print(date)
    }
}

【讨论】:

    猜你喜欢
    • 2014-11-29
    • 2018-02-06
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多