Swift 获取 GMT+08:00 时区的往年日期时间

Swift Get previous years datetime at GMT+08:00 timezone

我需要获得前 5 年的 GMT +08:00 时区,但我无法获得正确的时区。

 let today = NSDate()
    let gregorian = NSCalendar(calendarIdentifier: NSGregorianCalendar)

    gregorian?.timeZone = NSTimeZone(forSecondsFromGMT: 60*60*8)
    let offsetComponents = NSDateComponents()
    offsetComponents.year = years
    let nYearsDate: NSDate = gregorian!.dateByAddingComponents(offsetComponents, toDate: today, options: NSCalendarOptions(0))!

    println("getNYearsDate: \(nYearsDate)")

I am getting 2010-07-23 11:44:47 +0000 
instead of 2010-07-23 00:00:00 +0800

我需要得到

2010-07-23 00:00:00 +0800 和 2010-07-23 23:59:59 +0800

在上面的 Swift 和 iOS 7.1 中有没有办法实现这个?

您也需要重新设置时间。日期周期也最好用 NSDateComponents.

建模
// a little trick to get all calendar unit masks
let kAllCalendarUnits = NSCalendarUnit(rawValue: UInt.max)

// normalize the date
let components = NSCalendar.currentCalendar().components(
                 kAllCalendarUnits, fromDate: NSDate())
components.hour = 0
components.minute = 0
components.second = 0
let dateAtStartOfDay = NSCalendar.currentCalendar().dateFromComponents(components)!

// subtract 5 years
var period = NSDateComponents()
period.year = -5
let finalDate = NSCalendar.currentCalendar().dateByAddingComponents(period, 
                toDate: dateAtStartOfDay, options: [])!

请注意,无论该期间是否包含一个或两个闰年,带有日期组件的方法都会为您提供正确的日期。

剩下的就是如何显示这个日期的问题了。这是通过 NSDateFormatter 完成的。例如:

let formatter = NSDateFormatter()
formatter.timeZone = NSTimeZone(forSecondsFromGMT: 60 * 60 * 8)
formatter.dateFormat = "yyyy-MM-dd hh:mm:ss Z"
formatter.stringFromDate(finalDate)
// "2010-07-23 6:00:00 +0800"

如果您想知道为什么它说的是“6:00”而不是“8:00”:我运行此代码将我的机器设置为 GMT+1,加上夏令时 +1。显然,要获得“0:00”,您必须再次减去所需的时差,但在 GMT 时区,这将早 8 小时。