Время вывода не соответствует ожидаемому при использовании iOS SDK DateFormatter на дату, установленную на 1 января 1 - PullRequest
1 голос
/ 04 октября 2019

У меня есть сценарий, когда даты находятся на сервере без аспекта дня, и требуется только время. Поэтому элемент дня удаляется перед загрузкой на сервер. Разработка до этого момента (точка 1 в коде ниже) не может быть изменена, так как она поступает из внешнего источника, который уже находится в производстве.

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


//1.
//Taking a date with just hours and minutes as I don't need the date.
//The timezone set (Europe/Rome) is different from the machine (Europe/Malta)
//Issue below still occurs if we use the same timezone as the machine.
let date = Date(timeIntervalSinceReferenceDate: 1570168800) //Result: Oct 4, 2050 at 8:00 AM

var calendar = Calendar.current
calendar.timeZone = TimeZone(identifier: "Europe/Rome")!
let comps = calendar.dateComponents([.hour, .minute], from: date)

let strippedDate = calendar.date(from: comps)! //Result: Jan 1, 1 at 8:08 AM
//the date outputted is bypassing the timezone setting and using the machine timezone when stripping out the day
//and keeping hours and minutes alone

//2.
//Outputing the date back to the user in different timezone identifiers
//These timezone identiers are all in the same timezone
let dateFormatter = DateFormatter()
dateFormatter.timeStyle = .short;

dateFormatter.timeZone = TimeZone(identifier: "Europe/Paris")!
var formattedStart = dateFormatter.string(from: strippedDate) //Result: "7:19 AM"

dateFormatter.timeZone = TimeZone(identifier: "Europe/Rome")!
formattedStart = dateFormatter.string(from: strippedDate) //Result: "8:00 AM"
//This above appears correctly as it's coming from the same timezone that set up the starting date

dateFormatter.timeZone = TimeZone(identifier: "Europe/Malta")! 
formattedStart = dateFormatter.string(from: strippedDate) //Result: "8:08 AM"
//The above appears the same as the stripped date which is the same as the machine used to create the stripped date

dateFormatter.timeZone = TimeZone(identifier: "Europe/Madrid")!
formattedStart = dateFormatter.string(from: strippedDate) //Result: "6:55 AM"

Ссылка на этот ответ , эта проблема происходит "потому что в полдень 18 ноября 1883 года железнодорожные компании США и Канады начали использоватьновая, стандартная система времени ". Поэтому, поскольку дата сохраняется до этого события, это может быть причиной того, что мы получаем разные минуты. Однако я все еще не могу найти решение для вывода правильного времени.

...