SWIFT:如何为NSDate对象添加小时数 [英] SWIFT: How do I add hours to NSDate object

查看:474
本文介绍了SWIFT:如何为NSDate对象添加小时数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我从string生成一个NSDate对象。

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

我从网络服务器获取此字符串值。我需要修改个人设备时区。想要添加这个stringToDate对象但没有工作的时间

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)


推荐答案

你问错了问题。这就是所谓的 XY问题
你应该问如何在用户的本地时区显示我从网络服务器获得的日期字符串。

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 表示不包含时区的抽象形式的日期/时间。您将其转换为特定时区进行显示。不要尝试向NSDate添加/减去小时以抵消时区。这是错误的方法。

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.

正确答案很简单。创建第二个日期格式化程序,不要将其时区设置为GMT。它默认为用户的本地时区。

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

这篇关于SWIFT:如何为NSDate对象添加小时数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆