gpt4 book ai didi

ios - 如何计算当前月/年的天数

转载 作者:搜寻专家 更新时间:2023-11-01 05:46:42 25 4
gpt4 key购买 nike

NSDate/NSCalendar 是否有任何方法可以计算当前月份和当年的天数?

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

最佳答案

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

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)

关于ios - 如何计算当前月/年的天数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34843324/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com