【发布时间】:2020-04-06 09:39:40
【问题描述】:
我是 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 日期和时间转换为带偏移量的设备日期和时间格式
【问题讨论】:
-
使用文档中的代码有什么问题?
-
@Sweeper 正如我所说的 Swift 新手,没有经验,不知道如何实现它。我的意思是如何根据文档转换我的代码以动态传递区域。
-
只是不要手动设置
locale。它会自动设置为用户的语言环境。 -
你是这个意思吗?
ormater.locale = Locale(identifier: locale)到ormater.locale = Locale()?对不起,我很愚蠢。 -
我的意思是你应该完全删除那行。