如何在ios中获取今天日期的开始和结束时间?

Kru*_*tel 9 datetime nsdate nsdateformatter ios swift

我使用此代码获取当前日期和时间

    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))
Run Code Online (Sandbox Code Playgroud)

但我想得到今天约会的开始时间和结束时间

例如: 12-09-2016 00:00:00 AND 12-09-2016 23:59:59

如何获取当前日期的开始和结束时间?

Nir*_*v D 22

您可以使用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)
Run Code Online (Sandbox Code Playgroud)

编辑:将日期转换为字符串

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)
Run Code Online (Sandbox Code Playgroud)

  • **不要使用**`60*60*24`作为一天的持续时间.在夏令时的地区,一天可以有23,24或25小时.使用正确的日历方法,如http://stackoverflow.com/questions/13324633/nsdate-beginning-of-day-and-end-of-day的答案中所示. (3认同)