Swift:从Date Picker获取正确的时区? [英] Swift: Get correct time zone from Date Picker?
问题描述
我正在尝试使用时间格式化程序迅速从日期选择器中获取正确的时区,但它不起作用。我正在使用UTC,而不是EST。
I am trying to get the correct time zone from the date picker in swift using time formatter, it's not working. I'm getting UTC, not EST.
1)如果我打印dateFormatter.stringFromDate(datePicker)我得到了EST,但是
1) If I print dateFormatter.stringFromDate(datePicker) I get EST, but
2)我不知道不需要字符串,我需要在EST中使用NSDate,所以
2) I don't need a string, I need an NSDate in EST so
3)我可以使用它来获取EST中的timeIntervalSinceDate(NSDate)。
3) I can use it to get the timeIntervalSinceDate(NSDate) in EST.
我试图将其从字符串中带回NSDate的技巧如下所示,但没有用。它仍处于UTC,自日期起的时间间隔不正确。
My trick of trying to take it from string back to NSDate as seen below didn't work. It's still in UTC and the time interval since date is not right.
dateFormatter.locale = NSLocale.currentLocale()
dateFormatter.timeZone = NSTimeZone.localTimeZone()
dateFormatter.dateFormat = "yyyy-MM-dd HH:mm:ss"
let date: NSDate = dateFormatter.dateFromString(dateFormatter.stringFromDate(datePicker))!
print(date)
print(date.timeIntervalSinceDate(datePicker))
推荐答案
您不能通过日期选择器获取时区。您可以得到一个日期。该日期将取决于设备的当前时区。
You cannot "get a time zone" from a date picker. You can just get a date. The date will be independent on the current time zone of the device.
也许您认为您有不同的日期,但实际上,没有 UTC日期或 EST日期 。取而代之的是,只有一个日期,您可以使用日期格式器将其显示在各个时区。
Perhaps you think you have a different date, but actually, there is no such thing as a "UTC date" or "EST date". Instead, there is only one date, and you use date formatters to display them for various time zones.
请注意,您的代码中有很多冗余。日期格式化程序的默认语言环境和时区已经是您设置的相同值。另外,当您有一个返回 NSDate
的方法时,就没有用注释常量的方法:NSDate
Note that there is quite a bit of redundancy in your code. The default locale and time zone of a date formatter are already the same values that you set. Also, when you have a method that returns a NSDate
you do not have annotate the constant with : NSDate
, making your code more verbose and cluttered.
请注意,如果您 print
日期,则控制台将始终显示UTC。例如
Note that if you print
a date the console will always show UTC. e.g.
let date = NSDate() // Nov 10, 9:44 PM
let dateFormatter = NSDateFormatter()
dateFormatter.dateFormat = "YYYY-MM-dd hh:mm a"
let dateString = dateFormatter.stringFromDate(date) // "2015-11-10 09:44 PM"
print(date) // "2015-11-10 20:44:54 +0000\n"
这篇关于Swift:从Date Picker获取正确的时区?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!