【问题标题】:how to get start and end time from datepicker in swift?如何快速从日期选择器获取开始和结束时间?
【发布时间】:2017-01-20 17:14:30
【问题描述】:

我想从日期选择器中选择的日期获取开始和结束时间。

这是我的代码

 func handleDatePicker(sender: UIDatePicker) {
        let dateFormatter = NSDateFormatter()
    dateFormatter.dateFormat = "yyyy-MM-dd hh:mm:ss"

    let startOfDay = NSCalendar.currentCalendar().startOfDayForDate(sender.date)

    let components = NSDateComponents()
    components.hour   = 23
    components.minute = 59
    components.second = 59
    let endOfDay = NSCalendar.currentCalendar().dateByAddingComponents(components, toDate: startOfDay, options: NSCalendarOptions(rawValue: 0))
}

但我得到的输出类似于2016-10-12 12:00:00

我的问题是如何获得这样的输出

12-09-2016 00:00:00 AND 12-09-2016 23:59:59

【问题讨论】:

  • 检查this article。对我很有帮助
  • 你在这里得到什么输出 sender
  • 仅供参考:一天的结束不是 23:59:59。 iOS 可以处理纳秒,因此在 23:59:59 和 00:00:00 之间至少有 10 亿个可能的Dates。一天的结束因此被定义为第二天的开始。您应该计算第二天的开始时间(定义明确)并使用< 比较。

标签: ios swift nsdate nsdateformatter uidatepicker


【解决方案1】:

试试下面的代码:-

        let calendar = NSCalendar(calendarIdentifier:NSCalendarIdentifierGregorian)
        calendar?.timeZone =  NSTimeZone(abbreviation: "GMT")!
        let startOfDay = calendar?.startOfDayForDate(sender.date)

        print("startDay \(startOfDay)")
        let components = NSDateComponents()
        components.hour   = 23
        components.minute = 59
        components.second = 59
        components.timeZone =  NSTimeZone(abbreviation: "GMT")

        let endOfDay = calendar?.dateByAddingComponents(components, toDate: startOfDay!, options: NSCalendarOptions(rawValue: 0))
        print("end Day \(endOfDay)")

【讨论】:

  • 时区应该是默认的本地时区?
猜你喜欢
  • 2021-09-06
  • 2019-08-27
  • 2020-03-02
  • 2020-02-22
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2014-05-29
  • 1970-01-01
相关资源
最近更新 更多