This question already has an answer here:
这个问题在这里已有答案:
- NSDate beginning of day and end of day 16 answers
- NSDate从第16天开始到第16天结束
I am getting current date and time by using this code
我使用此代码获取当前日期和时间
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))
but i want to get start time and end time of today’s date
但我想得到今天约会的开始时间和结束时间
example : 12-09-2016 00:00:00 AND 12-09-2016 23:59:59
例如:12-09-2016 00:00:00和12-09-2016 23:59:59
How to get start and end time of current date?
如何获取当前日期的开始和结束时间?
1 个解决方案
#1
14
You can use startOfDayForDate
to get today's midnight date and then get end time from that date.
您可以使用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: Convert date to string
编辑:将日期转换为字符串
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)
#1
14
You can use startOfDayForDate
to get today's midnight date and then get end time from that date.
您可以使用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: Convert date to string
编辑:将日期转换为字符串
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)