[英]iOS Date() returns incorrect value
我正在使用以下代码获取 iOS 设备日期。
let today = Date()
let dateFormatter = DateFormatter()
dateFormatter.dateFormat = "dd"
let currentDate = dateFormatter.string(from: today)
print("todayDate : \(currentDate)")
dateFormatter.dateFormat = "MM"
let currentMonth = dateFormatter.string(from: today)
print("currentMonth : \(currentMonth)")
dateFormatter.dateFormat = "YYYY"
let currentYear = dateFormatter.string(from: today)
print("currentYear : \(currentYear)")
当我在 iPhone 设置 29-12-2019 或 30-12-2019 或 31-12-2019 中更改设备日期时。 currentMonth 和 currentDate 值是正确的。 但是,currentYear 返回值是 2020 年而不是 2019 年。请建议我解决这个问题。
一个常见的错误是使用 YYYY。 yyyy 指定日历年,而 YYYY 指定年份(“一年中的一周”),用于 ISO 年-周日历。 在大多数情况下,yyyy 和 YYYY 产生相同的数字,但它们可能不同。 通常,您应该使用日历年。 请参阅此帮助: DateFormatters 的挑战
使用您的日期格式
“yyyy”是普通日历年。
dateFormatter.dateFormat = "yyyy"
代替
“YYYY”是基于周的日历年。
dateFormatter.dateFormat = "YYYY"
最后根据你的问题,
let today = Date()
let dateFormatter = DateFormatter()
dateFormatter.dateFormat = "yyyy"
let currentYear = dateFormatter.string(from: today)
print("currentYear : \(currentYear)")
你得到的输出为
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.