-5

I am building an iOS app in Swift 2. I need to take a date and change the time for that date. How can I do that in the most simple way?

2016-12-10 12:00:00 to 2016-12-10 16:00:00

The time will come from a string but the date from an NSDate.

Jonathan Clark
  • 19,726
  • 29
  • 111
  • 175
  • 1
    Can you please post, what you have tried yet? Please provide a [Minimal, Complete, and Verifiable example](http://stackoverflow.com/help/mcve). – FelixSFD Dec 13 '16 at 13:38
  • Wow, so many down votes :( The reason I ask is that I do not know where to start. – Jonathan Clark Dec 13 '16 at 13:47
  • Why do you want to change the time. if it is to take timezone into account, it would be the wrong approach. And you should start with searching. – vikingosegundo Dec 13 '16 at 13:50
  • You can use some of the classes Apple provides for working with time. To create a `NSDate` from a `NSString` you need a `NSDateFormatter` (https://developer.apple.com/reference/foundation/nsdateformatter). Once you have your `NSString` converted to a `NSDate` you can add hours, minutes, seconds and so on by using a `NSCalendar` as described in this answer http://stackoverflow.com/a/29465300/4063602. Hope that gives you something to search for at least :) – pbodsk Dec 13 '16 at 13:52
  • This document is worth having a look at too: https://developer.apple.com/library/content/documentation/Cocoa/Conceptual/DatesAndTimes/DatesAndTimes.html – pbodsk Dec 13 '16 at 13:54
  • So you have an input date STRING in a particular format, and an input NSDate. You want to extract the time from the date string and then use that time and the NSDate and build a new NSDate that contains the time from the date string and the date from the input NSDate? – Duncan C Dec 13 '16 at 14:13

1 Answers1

1

Simplest way to get 16:00 local time:

let d1 = Date()
let d2 = Calendar.current.date(bySettingHour: 16, minute: 0, second: 0, of: d1)!

Note that if you call print(d2), it will always print in GMT so the hour may not show up as 16:00, but it's 16:00 in your local timezone.

Jenny
  • 2,041
  • 13
  • 15