我使用此代码获取当前日期和时间
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
如何获取当前日期的开始和结束时间?
答案 0 :(得分:20)
您可以使用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)
修改:将日期转换为字符串
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)