我使用此代码获取当前日期和时间
let today: NSDate = NSDate()
let dateFormatter: NSDateFormatter = NSDateFormatter()
dateFormatter.timeStyle = NSDateFormatterStyle.MediumStyle
dateFormatter.dateFormat = "yyyy-MM-dd hh:mm:ss"
dateFormatter.timeZone = NSTimeZone(abbreviation: "SGT");
print(dateFormatter.stringFromDate(today))
但我想获取今天日期的开始时间和结束时间
例子 :12-09-2016 00:00:00 AND 12-09-2016 23:59:59
如何获取当前日期的开始时间和结束时间?
您可以使用startOfDayForDate
获取今天的午夜日期,然后获取该日期的结束时间。
//For Start Date
let calendar = NSCalendar.currentCalendar()
calendar.timeZone = NSTimeZone(abbreviation: "UTC")! //OR NSTimeZone.localTimeZone()
let dateAtMidnight = calendar.startOfDayForDate(NSDate())
//For End Date
let components = NSDateComponents()
components.day = 1
components.second = -1
let dateAtEnd = calendar.dateByAddingComponents(components, toDate: startOfDay, options: NSCalendarOptions())
print(dateAtMidnight)
print(dateAtEnd)
Edit:将日期转换为字符串
let dateFormatter = NSDateFormatter()
dateFormatter.timeZone = NSTimeZone (abbreviation: "UTC")! // OR NSTimeZone.localTimeZone()
dateFormatter.dateFormat = "dd-MM-yyyy HH:mm:ss"
let startDateStr = dateFormatter.stringFromDate(dateAtMidnight)
let endDateStr = dateFormatter.stringFromDate(dateAtEnd)
print(startDateStr)
print(endDateStr)
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)