如何正确使用时区 [英] How to use TimeZone correctly
问题描述
我在 Swift 4 for iOS 中有以下代码
I have following code in Swift 4 for iOS
var dateComponents = DateComponents()
var datetime = Date()
dateComponents.timeZone = Calendar.current.timeZone
dateComponents.day = Calendar.current.component(.day, from: datetime)
dateComponents.month = Calendar.current.component(.month, from: datetime)
dateComponents.year = Calendar.current.component(.year, from: datetime)
dateComponents.hour = 12
dateComponents.minute = 45
datetime = Calendar.current.date(from: dateComponents)!
print(Calendar.current.timeZone)
print(datetime)
它产生这个输出:
欧洲/布拉格(当前)
2017-12-26 11:45:00 +0000
2017-12-26 11:45:00 +0000
虽然我期待
2017-12-26 12:45:00 +0000
2017-12-26 12:45:00 +0000
由于指定的时区.我必须以不同的方式做些什么?谢谢.
due to timezone specified. What I have to do differently? Thanks.
推荐答案
2017-12-26 11:45:00 +0000
正在向您显示 GMT/UTC/Zulu 中的日期(即+0000
是什么意思).最重要的是,2017 年 12 月 26 日下午 12:45 在布拉格是格林威治标准时间 11:45.
The 2017-12-26 11:45:00 +0000
is showing you the date in GMT/UTC/Zulu (that's what the +0000
means). Bottom line, 12:45pm on 26 Dec 2017 in Prague is 11:45 GMT.
Date
的 description
属性(如果你只是 print
一个 Date
,就会使用它)始终返回以 GMT 显示的字符串.如果您想在本地时区看到它,您可以使用日期格式化程序将日期转换为字符串,例如
The description
property of a Date
(which is what is used if you just print
a Date
) always returns a string shown in GMT. If you want to see it in your local timezone, you'd use a date formatter to convert a date to a string, e.g.
let formatter = DateFormatter()
formatter.dateStyle = .medium
formatter.timeStyle = .medium
print(formatter.string(from: datetime))
最重要的是,如果您想在应用的用户界面中显示日期(您想在本地时区中显示日期),请始终使用日期格式化程序.和DateComponents
一样,DateFormatter
的时区默认为当前时区.
Bottom line, if you want to display the date in the user interface of your app (where you want to show it in their local time zone), always use a date formatter. Like DateComponents
, the time zone of DateFormatter
defaults to the current time zone.
注意,我避免使用 DateFormatter
的 dateFormat
属性,因为每当在应用 UI 中显示日期字符串时,您都希望使用本地化字符串(显示在最终用户首选的格式,如设置"应用程序中指定的那样).实现此目的的最简单方法是使用 dateStyle
和 timeStyle
,如上所示.
Note, I avoided using dateFormat
property of the DateFormatter
because whenever showing a date string in an app UI, you want to use a localized string (the date shown in a format preferred by the end user, as specified in the Settings app). The easiest way to achieve this is use dateStyle
and timeStyle
as shown above.
这篇关于如何正确使用时区的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!