【问题标题】:How to calculate the number of days in the current month/year如何计算当前月/年的天数
【发布时间】:2016-01-17 20:34:07
【问题描述】:

NSDate/NSCalendar有什么方法可以计算当月和当年的天数吗?

我唯一看到的是从给定日期或两个日期之间获取天数。
这是唯一的方法吗?

【问题讨论】:

  • 但是我需要当前月份/年份,而不是给定月份,而且我实际上看不到一年中的天数是如何计算的。
  • 我确实希望人们能够证明投反对票是合理的,这样我就可以从错误中吸取教训,但从我的角度来看,这是一个很好的问题,我在 stackoverflow 上还找不到答案。
  • 我作为副本关闭,因为我认为链接到的答案在几个月和几年之前都有效。然后我意识到情况并非如此,因此我重新提出了这个问题。很抱歉造成混乱。

标签: ios swift


【解决方案1】:

这是一种适用于几个月和几年的方法:

let calendar = NSCalendar.currentCalendar()
let date = NSDate()

// Calculate start and end of the current year (or month with `.Month`):
var startOfInterval : NSDate?
var lengthOfInterval = NSTimeInterval()
calendar.rangeOfUnit(.Year, startDate: &startOfInterval, interval: &lengthOfInterval, forDate: date)
let endOfInterval = startOfInterval!.dateByAddingTimeInterval(lengthOfInterval)

// Compute difference in days:
let days = calendar.components(.Day, fromDate: startOfInterval!, toDate: endOfInterval, options: [])
print(days)

(你可能想要添加一些错误检查而不是强制解包 选项。)


Swift 3 更新:

let calendar = Calendar.current
let date = Date()

// Calculate start and end of the current year (or month with `.month`):
let interval = calendar.dateInterval(of: .year, for: date)!

// Compute difference in days:
let days = calendar.dateComponents([.day], from: interval.start, to: interval.end).day!
print(days)

【讨论】:

  • 是的,这适用于月份和年份(只需更改 rangeOfUnit 内的 .Year 字段)。谢谢。
【解决方案2】:
let date = NSDate()
let cal = NSCalendar(calendarIdentifier:NSCalendarIdentifierGregorian)!
let days = cal.rangeOfUnit(.Day, inUnit: .Month, forDate: date)

print("\(days) in the month of \(date)")

【讨论】:

  • 谢谢迈克尔。这很好用。如何计算一年中的天数?我尝试了相同的代码,但在 inUnit 字段中使用 .Year 而不是 .Month,但它似乎不起作用。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-05-09
  • 1970-01-01
  • 2020-12-01
  • 1970-01-01
  • 2021-02-18
相关资源
最近更新 更多