我是iOS新手。
我正在使用UTC YYYY-mm-dd H:i:s格式的时间。我想根据设备区域格式化和偏移日期和时间。
let utcdatestring = cat.created
let localdate = Validator.UTCToLocal(date: utcdatestring, fromFormat: "yyyy-MM-dd HH:mm:ss", toFormat: Constants.dateformat)
let localtime = Validator.UTCToLocal(date: utcdatestring, fromFormat: "yyyy-MM-dd HH:mm:ss", toFormat: Validator.gettimeformat())
let locale = Locale.current.identifier
let formater = DateFormatter()
formater.dateFormat = "dd-MMM-yyyy"
formater.locale = Locale(identifier: locale)
let showdate = formater.date(from: localdate)
let tformater = DateFormatter()
tformater.dateFormat = "hh:mm"
tformater.locale = Locale(identifier: locale)
let showtime = tformater.date(from: localtime)
我在苹果documentation上找到了某种方式,但是不确定如何在我的代码中实现。
let dateFormatter = DateFormatter()
dateFormatter.dateStyle = .medium
dateFormatter.timeStyle = .none
let date = Date(timeIntervalSinceReferenceDate: 118800)
// US English Locale (en_US)
dateFormatter.locale = Locale(identifier: "en_US")
print(dateFormatter.string(from: date)) // Jan 2, 2001
// French Locale (fr_FR)
dateFormatter.locale = Locale(identifier: "fr_FR")
print(dateFormatter.string(from: date)) // 2 janv. 2001
// Japanese Locale (ja_JP)
dateFormatter.locale = Locale(identifier: "ja_JP")
print(dateFormatter.string(from: date)) // 2001/01/02
问题:
如何将UTC日期和时间转换为带偏移的设备日期和时间格式
答案 0 :(得分:0)
let utcdatestring = cat.created
let localdate = Validator.UTCToLocal(date: utcdatestring, fromFormat: "yyyy-MM-dd HH:mm:ss", toFormat: Constants.dateformat)
let localtime = Validator.UTCToLocal(date: utcdatestring, fromFormat: "yyyy-MM-dd HH:mm:ss", toFormat: Validator.gettimeformat())
let formater = DateFormatter()
formater.dateFormat = "dd-MMM-yyyy"
let showdate = formater.date(from: localdate)
let tformater = DateFormatter()
tformater.dateFormat = "hh:mm"
let showtime = tformater.date(from: localtime)
尝试这样。我猜会自动设置区域设置