9

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

How to get start and end time of current date?

Nirav D
  • 71,513
  • 12
  • 161
  • 183
Krutarth Patel
  • 3,407
  • 6
  • 27
  • 54
  • 4
    `NSDate()` gives 'now'. You can utilise `NSDateComponents` and set the `hour` `minute` `second` and `nanosecond` components. Refer to [this](http://stackoverflow.com/q/13324633/2710486) – zc246 Sep 12 '16 at 11:58

1 Answers1

27

You can use startOfDayForDate to get today's midnight date and then get end time from that date.

//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)
Nirav D
  • 71,513
  • 12
  • 161
  • 183