I generate a NSDate object from string.
let dateFormatter = NSDateFormatter()
dateFormatter.dateFormat = \"yyyy-MM-dd HH:mm:ss\"
dateFormatter.timeZone = NS
For Swift 3 you can use this function:
//get next date by adding hours func
getNewDateAfterAddingHours(hoursToAdd:NSInteger, oldDate:Date) -> Int64 {
let calendar = Calendar.current
let newDate = calendar.date(byAdding: .hour, value: hoursToAdd, to: oldDate)
return Int64((newDate?.timeIntervalSince1970)!)
}
If you are doing it more often, check out library called SwiftMoment (inspired by the same .js library), which allows you to do following (and much more!):
// Create date using moment library
let myDate = moment(myString)
// Add one hour
let dateWithAddedHour = myDate + 1.hours
Moment is a wrapper around NSDate instance, while Duration (which is what you get from Int.hours, Int.minutes etc.) wraps an NSTimeInterval value.
Implementing this should take you just a moment! (Pun intended).
Use NSCalendarComponents
:
let calendar = NSCalendar.currentCalendar()
let newDate = calendar.dateByAddingUnit(
.CalendarUnitHour, // adding hours
value: 2, // adding two hours
toDate: oldDate,
options: .allZeros
)
Using NSCalendar
will account for things like leap seconds, leap hours, etc.
But as Duncan C's answer points out, simply adding hours is definitely the wrong approach. Two time zones won't always be separated by the same amount of time. Again, this is something especially true when we take daylight savings into account. (For example, the United States doesn't start/end daylight savings on the same days as Europe, and Arizona doesn't even do daylight savings).
You're asking the wrong question. This is what's known as an "XY Problem". You should be asking "How do I display a date string I get from a web server in the user's local time zone."
NSDate
represents a date/time in an abstract form that does not contain a time zone. You convert it to a specific time zone for display. Do not try to add/subtract hours to an NSDate to offset for time zones. That is the wrong approach.
The correct answer is simple. Create a second date formatter and don't set it's timezone to GMT. It defaults to the user's local time zone.
let dateFormatter = NSDateFormatter()
dateFormatter.dateFormat = "yyyy-MM-dd HH:mm:ss"
dateFormatter.timeZone = NSTimeZone(abbreviation: "GMT")
let date = dateFormatter.dateFromString(dateFromService)
let outputDatedateFormatter = NSDateFormatter()
outputDatedateFormatter.dateFormat = "yyyy-MM-dd HH:mm:ss"
//leave the time zone at the default (user's time zone)
let displayString = outputDateFormatter.stringFromDate(date)
println("Date in local time zone = \(displayString)")