我在数据库中有很多不同的显示时间,并希望通过创建偏移量来根据用户时区显示正确的时间.
我从GMT获得用户时区偏移并将其转换为小时数.
NSTimeZone.localTimeZone().secondsFromGMT / 60 / 60
Run Code Online (Sandbox Code Playgroud)
然后我需要找到一种方法来将日期对象添加到日期对象中......这就是我/我挣扎的地方.
let formatter = NSDateFormatter()
formatter.dateFormat = "HH:mm"
let date = formatter.dateFromString(timeAsString)
println("date: \(date!)")
Run Code Online (Sandbox Code Playgroud)
然后我从标签中创建一个字符串,以便用AM/PM轻松读取.
formatter.dateFormat = "H:mm"
formatter.timeStyle = .ShortStyle
let formattedDateString = formatter.stringFromDate(date!)
println("formattedDateString: \(formattedDateString)")
Run Code Online (Sandbox Code Playgroud)
我似乎无法找出如何添加/减去小时数.我把弦分开了,但有时候会变成负面而且不起作用.也许我错了.
谢谢你的帮助.
基思
我需要将NSTimeInterval类型的变量(我知道是Double)转换为Integer.我已经尝试过这里的解决方案:如何将NSTimeInterval转换为int?,没有成功.任何人都可以在Swift中提供有关如何执行此操作的任何建议吗?以下是我的功能:
func getHKQuantityData(sampleType: HKSampleType, timeUnit: NSCalendarUnit, startDate: NSDate, endDate: NSDate, completion: (Void -> Void)) -> [(NSDate, Double)] {
var startTime = 0
var endTime = 0
var repeat: NSTimeInterval
var returnValue: [(NSDate, Double)] = []
var queryType: String = ""
var predicate: NSPredicate!
let timeInterval = endDate.timeIntervalSinceDate(startDate)
switch sampleType {
case HKSampleType.quantityTypeForIdentifier(HKQuantityTypeIdentifierStepCount):
queryType = "step"
case HKSampleType.quantityTypeForIdentifier(HKQuantityTypeIdentifierHeight):
queryType = "height"
case HKSampleType.quantityTypeForIdentifier(HKQuantityTypeIdentifierBodyMass):
queryType = "weight"
case HKSampleType.quantityTypeForIdentifier(HKQuantityTypeIdentifierBodyMassIndex):
queryType = "bmi"
default:
println("No recognized type")
}
switch timeInterval { …Run Code Online (Sandbox Code Playgroud)