How To Use TimeZone Correctly
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)
and it produces this output:
2017-12-26 11:45:00 +0000
whilst I expect
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 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.
description property of a
Date (which is what is used if you just
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))
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.
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
timeStyle as shown above.
- → Function Undefined in Axios promise
- → What are the pluses/minuses of different ways to configure GPIOs on the Beaglebone Black?
- → Click to navigate on mobile devices
- → Playing Video - Server is not correctly configured - 12939
- → How to allow api access to android or ios app only(laravel)?
- → Axios array map callback
- → Access the Camera and CameraRoll on Android using React Native?
- → Update React [Native] View on Day Change
- → Shopify iOS SDK - issue converting BuyProductVariant to BuyProduct
- → BigCommerce and shopify API
- → Warning: Each child in an array or iterator should have a unique "key" prop. Check the render method of `ListView`
- → React Native - Differences between Android and IOS
- → What is the difference between React Native and React?