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

标签: ios swift


【解决方案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"会自动根据设备改变格式吗?
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-12-06
  • 2015-04-13
  • 1970-01-01
  • 2017-10-10
  • 2011-05-18
  • 1970-01-01
相关资源
最近更新 更多