Как установить пользовательский часовой пояс из значения индекса часового пояса Microsoft в Swift?

В моем случае использования я получаю значение индекса часового пояса Microsoft. Индекс вы найдете здесь. Мне нужен этот индекс, чтобы получить часовой пояс элемента.

Чтобы установить собственный часовой пояс в Swift, я только что нашел этот фрагмент.

dateformatter.timeZone =  NSTimeZone(abbreviation: "CEST") 

И здесь я нашел список со всеми сокращениями

ADT = "America/Halifax";
AKDT = "America/Juneau";
AKST = "America/Juneau";
ART = "America/Argentina/Buenos_Aires";
AST = "America/Halifax";
BDT = "Asia/Dhaka";
[...]
WET = "Europe/Lisbon";
WIT = "Asia/Jakarta";

Так что у меня есть вся информация. Время в формате UTC/GMT. Значение индекса и все возможные часовые пояса в Swift. Но я не могу понять, какой часовой пояс для чего.

Например, в значениях индекса часовых поясов Microsoft указано 001 «Стандартное время Самоа — GMT-11:00 Остров Мидуэй, Самоа».

Но что это в быстром? Я не могу сделать что-то вроде

dateformatter.timeZone =  NSTimeZone(abbreviation: "GMT-11") //not found the abbreviation

У кого-нибудь есть идеи или предложения по решению проблемы?


person kuzdu    schedule 12.07.2016    source источник
comment
Обратите внимание, что если вы действительно не используете Windows Embedded POS 1.1 2006 года, статья, на которую вы ссылаетесь, не применяется, а числовые значения, такие как 001, больше не используются. На эту конкретную статью часто ссылаются, но она не обновлялась в течение 10 лет и не соответствует тому, что используется в современной ОС Windows.   -  person Matt Johnson-Pint    schedule 12.07.2016


Ответы (3)


У меня есть решение, которое может помочь, но оно немного хакерское и не самое чистое. Поскольку вы можете получить словарь значений аббревиатур из NSTimeZone, мы можем повторить это в цикле for. Если у вас есть аббревиатура, которую мы можем подключить к NSTimeZone(abbreviation:), мы можем найти секунды для GMT, используя .secondsFromGMT, а затем создать оператор if, чтобы проверить, является ли это GMT, который мы ищем. Ее рабочий пример:

// Get the full name and abbreviation from the NSTimeZone dictionary
for (abbreviation, fullName) in NSTimeZone.abbreviationDictionary() {

    // Plug the abbreviation into NSTimeZone and get the seconds from GMT and match it to the GMT we want (in this case, GMT+8)
    if NSTimeZone(abbreviation: abbreviation)?.secondsFromGMT == 28800 {

        // Print the result if a match was found.
        print(fullName)

    }

}
person Camon    schedule 12.07.2016

Я пытаюсь выполнить код ниже, чтобы добиться этого

Свифт

let calendar: NSCalendar = NSCalendar.currentCalendar()
calendar.timeZone = NSTimeZone(name: "Pacific/Midway")!

Цель-C

 NSCalendar *calendar = [NSCalendar currentCalendar];
[calendar setTimeZone:[NSTimeZone timeZoneWithName:@"Pacific/Midway"]];
 NSLog(@"calendar timezone: %@", calendar.timeZone);

Output: 
calendar timezone: Pacific/Midway (GMT-11) offset -39600

// You will set timeZone Pacific/Apia and get below output is GMT +13
calendar timezone: Pacific/Apia (GMT+13) offset 46800

И я ссылался на ссылки ниже. Сначала вы знаете специальную аббревиатуру для всего часового пояса.

1.http://www.unicode.org/cldr/charts/29/supplemental/zone_tzid.html

2. Преобразование имен часовых поясов в идентификаторы времени в Xcode< /а>

person HariKrishnan.P    schedule 12.07.2016

Поэтому я нашел решение, которое сработало для меня.

Если вам нужны секунды от GMT и у вас есть индекс стоимости Microsoft:

func getTimeZoneShorthandSymbol(index: Int) -> Double {


    var gmtnumber = 0.0

    if index == 000 {
        gmtnumber = 12
    } else if index == 001 {
        gmtnumber = 11
    } else if index == 002 {
        gmtnumber = 10
    } else if index == 003 {
        gmtnumber = 9
    } else if index == 004 {
        gmtnumber = 8
    } else if index == 010 || index == 013 || index == 015 {
        gmtnumber = 7
    } else if index == 020 || index == 025 || index == 030 || index == 033 {
        gmtnumber = 6
    } else if index == 035 || index == 040 || index == 045 {
        gmtnumber = 5
    } else if index == 050 || index == 055 || index == 056 {
        gmtnumber = 4
    } else if index == 060 {
        gmtnumber = 3.5
    } else if index == 065 || index == 070 || index == 073  {
        gmtnumber = 3
    } else if index == 075 {
        gmtnumber = 2
    } else if index == 080 || index == 083 {
        gmtnumber = 1
    } else if index == 085 || index == 090 {
        gmtnumber = 0
    } else if index == 095 || index == 100 || index == 105 || index == 110 || index == 113 {
        gmtnumber = 1
    } else if index == 115 || index == 120 || index == 125 || index == 130 || index == 135 || index == 140 {
        gmtnumber = 2
    } else if index == 145 || index == 150 || index == 155 || index == 158 {
        gmtnumber = 3
    } else if index == 160 {
        gmtnumber = 3.5
    } else if index == 165 || index == 170 {
        gmtnumber = 4
    } else if index == 175 {
        gmtnumber = 4.5
    } else if index == 180 || index == 185  {
        gmtnumber = 5
    } else if index == 190 {
        gmtnumber = 5.5
    } else if index == 193 {
        gmtnumber = 5.75
    } else if index == 195 || index == 200 || index == 201 {
        gmtnumber = 6
    } else if index == 203 {
        gmtnumber = 6.5
    } else if index == 205 || index == 207 {
        gmtnumber = 7
    } else if index == 210 || index == 215 || index == 220 || index == 225 || index == 227 {
        gmtnumber = 8
    } else if index == 230 || index == 235 || index == 240 {
        gmtnumber = 9
    } else if index == 245 || index == 250 {
        gmtnumber = 9.5
    } else if index == 255 || index == 260 || index == 265 || index == 270 || index == 275 {
        gmtnumber = 10
    } else if index == 280 {
        gmtnumber = 11
    } else if index == 285 || index == 290 {
        gmtnumber = 12
    } else if index == 300 {
        gmtnumber = 13
    }

    return gmtnumber*60*60
    }

Будьте осторожны: это показывает только стандартную разницу. Там нет обработки летнего времени или чего-то еще. Я им не пользовался, но мне пришлось так много печатать... может быть, кому-то это когда-нибудь понадобится.

Мое решение: у меня было три даты: UTC, время (зона) моего предмета и мое местное время.

Я взял разницу между UTC и моим товаром.

var m = Model.sharedInstance().minutesFrom(dateFromUtc, sndDate: from) //get difference between two dates in minutes

                if m < 0 {
                    m = m * (-1) //m should be always positiv
                }
              let secondsDiffernce =  m * 60 //to seconds

func minutesFrom(date: NSDate, sndDate: NSDate) -> Int{
    return NSCalendar.currentCalendar().components(.Minute, fromDate: date, toDate: sndDate, options: []).minute
}

Далее мне нужна разница между utc и моим местным часовым поясом

let secondsFromLocalTimeZone = NSTimeZone.localTimeZone().secondsFromGMT

С этой информацией я могу создавать разные даты даты, например:

//utc time
let calendar = NSCalendar.currentCalendar()
                let components = NSDateComponents()
                components.day = 12
                components.month = 01
                components.year = 2016
                components.hour = 11
                components.minute = 53


                components.timeZone = NSTimeZone(forSecondsFromGMT: 25200) //set here your seconds from item, localtime whatever...

Покажите дату по вашему выбору

let newDate = calendar.dateFromComponents(components)

Спасибо за помощь!

person kuzdu    schedule 12.07.2016