我正在尝试使用NSDateFormatter从日期中删除时间。这是代码:
func dateWithOutTime( datDate: NSDate?) -> NSDate {
let formatter = NSDateFormatter()
formatter.dateFormat = "dd-MM-yyyy"
let stringDate: String = formatter.stringFromDate(datDate!)
let dateFromString = formatter.dateFromString(stringDate)
return dateFromString!
}
如果我在04-01-2016 12:00:00之前寄出,则返回03-01-2016 23:00:00 我已经尝试过更改dateFormat,但它仍然会从日期减去一天...为什么?请帮助:)
答案 0 :(得分:4)
最简单的方法是使用startOfDayForDate
NSCalendar
斯威夫特2:
func dateWithOutTime( datDate: NSDate) -> NSDate {
return NSCalendar.currentCalendar().startOfDayForDate(datDate)
}
Swift 3 +:
func dateWithOutTime(datDate: Date) -> Date {
return Calendar.current.startOfDay(for: datDate)
}
或将时区调整为UTC / GMT
斯威夫特2:
func dateWithOutTime( datDate: NSDate) -> NSDate {
let calendar = NSCalendar(identifier: NSCalendarIdentifierGregorian)!
calendar.timeZone = NSTimeZone(forSecondsFromGMT: 0)
return calendar.startOfDayForDate(datDate)
}
Swift 3 +:
func dateWithOutTime(datDate: Date) -> Date {
var calendar = Calendar(identifier: .gregorian)
calendar.timeZone = TimeZone(secondsFromGMT: 0)!
return calendar.startOfDay(for: datDate)
}
答案 1 :(得分:1)
两件事:
(a)这可以在不使用NSDateFormatter
的情况下完成。 (b)拨打print(aDate)
会给你UTC时间,而不是当地时间。在失去过多脑细胞试图在心理上来回转换之后,我决定对NSDate
进行扩展,以便在当地时区打印出来。
// NSDateFormatter is expensive to create. Create it once and reuse
let dateFormatter = NSDateFormatter()
dateFormatter.locale = NSLocale.currentLocale()
dateFormatter.dateFormat = "yyyy-MM-dd HH:mm:ss ZZZZ"
extension NSDate {
// This will print the date in the local timezone
var localTime: String {
return dateFormatter.stringFromDate(self)
}
}
func dateWithOutTime(datDate: NSDate?) -> NSDate {
let calendar = NSCalendar.currentCalendar()
let components = calendar.components([.Year, .Month, .Day], fromDate: datDate!)
return calendar.dateFromComponents(components)!
}
let datDate = NSCalendar.currentCalendar().dateWithEra(1, year: 2016, month: 1, day: 4, hour: 12, minute: 0, second: 0, nanosecond: 0)
let result = dateWithOutTime(datDate)
print(result.localTime)