It seems setDefaultTimeZone
method is no longer available in NSTimeZone
. Does someone know a substitute for this?
In my AppDelegate.swift
, I have:
NSTimeZone.default = TimeZone(abbreviation: "BST")!
and it works as intended I guess because in all the other files, I get NSTimeZone
set to this value
Now, In my Utils, I have this method:
static func getDate(_ dateStr: String) -> Date {
let dateFormatter = DateFormatter()
dateFormatter.dateFormat = "yyyy-MM-dd"
// dateFormatter.timeZone = TimeZone(abbreviation: "GMT")
let date = dateFormatter.date(from: dateStr)!
return date
}
So, lets say, I give it input 2016-10-07
, it gives me back 2016-10-06 23:00
. Why? It gets fixed if you uncomment the line in the above code. I don't want to use this line everywhere.
For example, in some other part of my project, I have used CVCalendar
. It provides a function for getting convertedDate like so
func didSelectDayView(_ dayView: DayView, animationDidFinish: Bool) {
selectedDay = dayView
selectedDate = dayView.date.convertedDate()!
}
The same thing as before is happening here too...that is I click on 2016-10-08
and it selectedDate
here becomes 2016-10-07 23:00
.
And the NSTimeZone.Default
prints Europe/London
everywhere.
Does anyone have any idea why is this happening?
Try like this.
TimeZone.ReferenceType.default = TimeZone(abbreviation: "BST")!
Edit: I have used this TimeZone
with DateFormatter
and get the correct BST
time with date.
TimeZone.ReferenceType.default = TimeZone(abbreviation: "BST")!
let formatter = DateFormatter()
formatter.timeZone = TimeZone.ReferenceType.default
formatter.dateFormat = "yyyy-MM-dd HH:mm"
let strDate = formatter.string(from: Date())
print(strDate)
If you want to set defaultTimeZone
for NSTimeZone
object then in Swift 3 you can set like this.
NSTimeZone.default = TimeZone(abbreviation: "BST")!
let locale = NSTimeZone.init(abbreviation: "BST")
NSTimeZone.default = locale as! TimeZone
Try this
If you are using calendar then,
// * create calendar object *
var calendar = NSCalendar.current
// * define calendar components to use as well Timezone to UTC *
let unitFlags = Set<Calendar.Component>([.hour, .year, .minute])
calendar.timeZone = TimeZone(identifier: "UTC")!
/// Returns a time zone initialized with a given identifier. /// /// An example identifier is "America/Los_Angeles". /// /// If `identifier` is an unknown identifier, then returns `nil`. public init?(identifier: String)
The geopolitical region identifier that identifies the time zone.
public var identifier: String { get }
Note : If you want to set the date formatter timezone, you can follow the above approach like this :
dateFormatter.timeZone = TimeZone(identifier: "UTC")!
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With