Получение неверной даты при преобразовании строки с часовым поясом - PullRequest
0 голосов
/ 10 января 2019

В Swift Playground я запускаю это.

let string = "2019-01-14T00:00:00+08:00"
let utcTimezone = TimeZone(abbreviation: "UTC")!
let sgtTimezone = TimeZone(abbreviation: "SGT")!

let dfs = DateFormatter()
dfs.timeZone = sgtTimezone
dfs.locale = Locale(identifier: "en_sg")
dfs.dateFormat = "yyyy-MM-dd'T'HH:mm:ssZZZ"
dfs.calendar = Calendar(identifier: Calendar.Identifier.iso8601)

let date = dfs.date(from: string)!

Почему дата = Jan 13, 2019 at 11:00 PM, а не точная 14 января 2019 года в 00:00?

Попытка изменить часовой пояс на UTC, но по умолчанию результат UTC Я ожидаю Jan 14, 2019 at 00:00 AM .. или, по крайней мере, 14 января

1 Ответ

0 голосов
/ 10 января 2019
// This lets us parse a date from the server using the RFC3339 format
let rfc3339DateFormatter = DateFormatter()
rfc3339DateFormatter.locale = Locale(identifier: "en_US_POSIX")
rfc3339DateFormatter.dateFormat = "yyyy-MM-dd'T'HH:mm:ssZZZZZ"
rfc3339DateFormatter.timeZone = TimeZone(secondsFromGMT: 0)

// This string is just a human readable format. 
// The timezone at the end of this string does not mean your date 
// will magically contain this timezone. 
// It just tells the parser what timezone to use to convert this 
// string into a date which is basically just seconds since epoch.
let string = "2019-01-14T00:00:00+08:00"

// At this point the date object has no timezone
let shiftDate = rfc3339DateFormatter.date(from: string)!

// If you want to keep printing in SGT, you have to give the formatter an SGT timezone.
let printFormatter = DateFormatter()
printFormatter.dateStyle = .none
printFormatter.timeStyle = .full
printFormatter.timeZone = TimeZone(abbreviation: "SGT")!
let formattedDate = printFormatter.string(from: shiftDate)

Вы заметите, что он печатает 12:00. В вашем коде нет ничего плохого. Вы просто неправильно понимаете объект Date. Большинство людей делают.

Редактировать: я использовал форматер RFC, который можно найти в документации Apple здесь . Результат тот же, если вы используете ваш форматтер. И да, как сказал Рматти, с вашим форматером есть несколько ошибок (я исправлен:))

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...