HamdyAli
HamdyAli

Reputation: 173

Getting the timezone (GMT) in Swift

I have an app that displays the timezones of different countries. Currently the code looks like this:

if indexPath.row == 0 || indexPath.row == 1 || indexPath.row == 2 || indexPath.row == 6 || indexPath.row == 7{
    cell.aseanDate.text = dayFormatter.string(from: Date() as Date)
    cell.aseanTime.text = dateFormatter2.string(from: Date() as Date)
    cell.aseanTime.textAlignment = .center
    cell.aseanTimeZone.text = "\(TimeZone(abbreviation: "UTC+07")!)"
}

The time itself is displayed properly but underaseanTimezone.text it displays GMT +0800(fixed)

Is it possible to change it so it displays the GMT but without the first zero and the word (fixed)?

Upvotes: 3

Views: 3857

Answers (2)

Satish
Satish

Reputation: 2043

I think you are looking for this method

localizedName(for style: NSTimeZone.NameStyle, locale: Locale?)

But, it will remove the trailing zeros too GMT+7

TimeZone(abbreviation: "UTC+07")!.localizedName(for: .shortStandard, locale: nil)! // => GMT+7

Other available options

.standard
.shortStandard
.daylightSaving
.shortDaylightSaving
.generic
.shortGeneric

Upvotes: 6

user10579845
user10579845

Reputation:

Try this below code

if indexPath.row == 0 || indexPath.row == 1 || indexPath.row == 2 || indexPath.row == 6 || indexPath.row == 7 {
    let newDate = Date()
    formatter.dateStyle = .none
    formatter.timeStyle = .short
    formatter.dateFormat = "hh:mm a"
    formatter.timeZone = TimeZone(identifier:"Your timezoon string here!!")
    cell.aseanTimeZone.text = = formatter.string(from: newDate)
} 

Upvotes: 0

Related Questions