SWIFT: How do I add hours to NSDate object

对着背影说爱祢 提交于 2019-12-30 04:39:21

问题


I generate a NSDate object from string.

let dateFormatter = NSDateFormatter()
dateFormatter.dateFormat = "yyyy-MM-dd HH:mm:ss"
dateFormatter.timeZone = NSTimeZone(abbreviation: "GMT")
let stringToDate = dateFormatter.dateFromString(dateFromService) // 2015-07-20 12:00:43 +0000

I get this string value from webserver. I need to modify for personal device timezone. Want to add hours this stringToDate object but not work

var addHours : Int = 2 // 2 hours will be added
var newDate = stringToDate.dateByAddingTimeInterval(addHours)

回答1:


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)")



回答2:


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).




回答3:


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)!)
}



回答4:


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).



来源:https://stackoverflow.com/questions/31516146/swift-how-do-i-add-hours-to-nsdate-object

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!