Swift - iOS UTC 日期和时间设置为带有偏移的设备日期和时间格式

Posted

技术标签:

【中文标题】Swift - iOS UTC 日期和时间设置为带有偏移的设备日期和时间格式【英文标题】:Swift - iOS UTC date and time set with the device date and time format with offset 【发布时间】: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() ?对不起,我很愚蠢。 我的意思是你应该完全删除那行。 【参考方案1】:
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)

试试这样。我猜语言环境会自动设置

【讨论】:

但是在设置日期格式的时候formater.dateFormat = "dd-MMM-yyyy"会自动根据设备改变格式吗?

以上是关于Swift - iOS UTC 日期和时间设置为带有偏移的设备日期和时间格式的主要内容,如果未能解决你的问题,请参考以下文章

如何在 Swift 中解析/创建格式为小数秒 UTC 时区(ISO 8601、RFC 3339)的日期时间戳?

如何在 Swift 中解析/创建格式为小数秒 UTC 时区(ISO 8601、RFC 3339)的日期时间戳?

DateTime<Utc> 编译但不是 DateTime<Local> 查询表,其列定义为带时区的时间戳

iOS,Swift中UTC登机时间与当前时间之间的差异

iOS:将 UTC NSDate 转换为本地时区

在 iOS 中将 UTC 日期时间转换为本地日期时间