ios - 从 Int 组件创建 NSDate

标签 ios swift

我有一个用于选择日期的日历:

func SACalendarDate(calendar: SACalendar!, didSelectDate day: Int32, month: Int32, year: Int32) {
    var date = Date.from(year: Int(year), month: Int(month), day: Int(day))

    print("\(year) and \(month) and \(day)")

    let formatter = NSDateFormatter()
    formatter.dateStyle = NSDateFormatterStyle.MediumStyle
    formatter.timeStyle = NSDateFormatterStyle.NoStyle
    let dateString = formatter.stringFromDate(date)

    buttonSelectDates.setTitle("\(dateString)", forState: UIControlState.Normal)
    getUsers(date)
}

当我用这种方法输入“日期”时:

class func from(#year:Int, month:Int, day:Int) -> NSDate {
    var c = NSDateComponents()
    c.year = year
    c.month = month
    c.day = day

    var gregorian = NSCalendar(identifier:NSCalendarIdentifierGregorian)
    var date = gregorian!.dateFromComponents(c)
    return date!
}

我得到一个晚一天的日期:selectedDate: 2015-07-14 22:00:00 +0000 而参数是:2015、7、15,为什么会这样?

最佳答案

NSDate 只是一个时间点,表示自 1970 年 1 月 1 日以来的秒数,它不关心时区或任何东西 - 它的“时区”是 GMT 并且是 +0000(无偏移)。如果您从具有本地时区的日历创建一个 NSDate,例如 +0200,该时区偏移将从您提供的实际日期中扣除,以表示没有任何时区的时间点。要返回 NSDate 的可读日期表示,您需要使用知道您当前时区的 NSDateFormatter:

let date = from(2015, month: 7, day: 15)
let dateFormatter = NSDateFormatter()
dateFormatter.dateFormat = "yyyy-MM-dd HH:mm:ss Z"

print(dateFormatter.stringFromDate(date))
print(date)

您将收到以下打印输出:

2015-07-15 00:00:00 +0200
2015-07-14 22:00:00 +0000

关于ios - 从 Int 组件创建 NSDate,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31232848/

相关文章:

ios - 如何调试 iOS 扩展 (.appex)?

ios - Realm 一对多关系仅在 Swift 3 for iOS 中单方面工作

ios - 在 Swift 中将对象从一个类移动到另一个类

swift - 返回动态通用类型

ios - 如何在 SWIFT 3 或 4 中的 REST API 调用期间安全地处理 cookie?

ios - 显示警报 View 时按钮更改位置

ios - 混淆 iPhone 密码

ios - 在 Cordova/WatchKit 应用程序上导入 MMWormhole

ios - 如何使用 SpriteKit 使球仅垂直而不是水平弹跳?

ios - 更改 View Controller 时,新 Controller 出现,但几乎立即消失