在 swift 中将 NSDate 设置为 0 秒

Set NSDate 0 seconds in swift

我正在尝试从 UIDatePicker 获取 NSDate,但它总是 returns 给我一个尾随 20 秒的日期时间。如何在 swift 中手动将 NSDate 的秒设置为零?

来自answer Swift:

var date = NSDate();
let timeInterval = floor(date .timeIntervalSinceReferenceDate() / 60.0) * 60.0
date = NSDate(timeIntervalSinceReferenceDate: timeInterval)

只需重新格式化日期:

func stripSecondsFromDate(date: NSDate) -> NSDate {
  let dateFormatter = NSDateFormatter()
  dateFormatter.dateFormat = "yyyy-MM-dd HH:mm"
  let str = dateFormatter.stringFromDate(date)
  let newDate = dateFormatter.dateFromString(str)!

  return newDate
}

可以使用

将日期截断为一整分钟
let date = NSDate()

let cal = NSCalendar.currentCalendar()
var fullMinute : NSDate?
cal.rangeOfUnit(.CalendarUnitMinute, startDate: &fullMinute, interval: nil, forDate: date)
println(fullMinute!)

Swift 4 及更高版本的更新:

let date = Date()
let cal = Calendar.current
if let fullMinute = cal.dateInterval(of: .minute, for: date)?.start {
    print(fullMinute)
}

此方法可以很容易地调整为截断为完整的小时、天、月...

这是Swift3中的做法。

在此示例中,我删除了日期组件中的秒数:

let date = picker.date
let calendar = Calendar.current
let components = calendar.dateComponents([.year, .month, .day, .hour, .minute], from: date)
let fullMinuteDate = calendar.date(from: components)!

在操场上工作:

extension Date {

    var zeroSeconds: Date? {
        let calendar = Calendar.current
        let dateComponents = calendar.dateComponents([.year, .month, .day, .hour, .minute], from: self)
        return calendar.date(from: dateComponents)
    }

}

用法:

let date1 = Date().zeroSeconds

let date2 = Date()
print(date2.zeroSeconds)
import Foundation

let now = Date()
let calendar = Calendar.current
let date = calendar.date(bySettingHour: 0,
                         minute: 0,
                         second: 0,
                         of: now,
                         direction: .backward)

还有一种方式,多了两个参数:matchingpolicy and repeatedTimePolicy.

let date = calendar.date(bySettingHour: 0,
                         minute: 0,
                         second: 0,
                         of: now,
                         matchingPolicy: .strict,
                         repeatedTimePolicy: .first,
                         direction: .backward)

查看结果:

let formatter = ISO8601DateFormatter()
formatter.timeZone = TimeZone.current // defaults to GMT
let string = formatter.string(from: date!)
print(string) // 2019-03-27T00:00:00+01:00

我知道这不会直接解决 NSDate,但无论如何它可能是值得的 - 我在 Date 上遇到了完全相同的问题,而且因为我认为这 可能 是一种更 干净 的方法。

extension Calendar {
    /// Removes seconds `Calendar.Component` from a `Date`. If `removingFractional` is `true`, it also
    /// removes all fractional seconds from this particular `Date`.
    ///
    /// `removingFractional` defaults to `true`.
    func removingSeconds(fromDate date: Date, removingFractional removesFractional: Bool = true) -> Date? {
        let seconds = component(.second, from: date)
        let noSecondsDate = self.date(byAdding: .second, value: -seconds, to: date)

        if removesFractional, let noSecondsDate = noSecondsDate {
            let nanoseconds = component(.nanosecond, from: noSecondsDate)
            return self.date(byAdding: .nanosecond, value: -nanoseconds, to: noSecondsDate)
        }

        return noSecondsDate
    }
}

现在,为了解决您的问题,我们创建了函数 removingSeconds(fromDate: removingFractional)。它真的很简单 - 正如您在函数的文档中看到的那样。它删除 .second 组件,如果 removingFractionaltrue,它还会删除此 Date 可能具有的任何小数秒 - 或 .nanosecond 组件。