gpt4 book ai didi

ios - 如何在所有时区/地区向 NSCalendar 添加天数

转载 作者:行者123 更新时间:2023-11-28 19:40:45 26 4
gpt4 key购买 nike

我在 Swift 2.0 中有以下代码块,我使用它从当前日期开始添加 3 天以检索该特定日期的天气数据。

var inThreeDaysValue: String {
let newDate = NSCalendar.currentCalendar().dateByAddingUnit(.Day, value: 3,
toDate: currentDate, options: NSCalendarOptions.init(rawValue: 0))

dateFormatter.dateFormat = "YYYY-MM-dd"

print("*** IN THREE DAYS \(dateFormatter.stringFromDate(newDate!))")
return "\(dateFormatter.stringFromDate(newDate!)) 12:00:00"

}

事实是,如果我在我的模拟器中运行此代码(使用“美国”作为区域),新日期将设置为提前 3 天和 1 年(如果今天是 < em>2015-12-24 新日期将是 2016-12-27)。

相反,如果我将模拟器的区域设置为“英国”或“意大利”,代码将完美执行并且新日期是准确的。

我想知道为什么会发生这种情况,以及是否有办法让这段代码在 iOS 9.2 提供的所有时区和地区工作

最佳答案

将 YYYY 改为小写,如下所示:

dateFormatter.dateFormat = "yyyy-MM-dd"

这个问题的描述是:

One major thing to note, there is a difference between “yyyy” and “YYYY”. In most cases, you probably want to use the lowercase one, “yyyy”. The uppercase one is the “Week of Year” style of year.

您可以在这里阅读所有相关信息: http://www.codingexplorer.com/swiftly-getting-human-readable-date-nsdateformatter/

祝你好运:)

关于ios - 如何在所有时区/地区向 NSCalendar 添加天数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34451763/

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