簡體   English   中英

Swift - iOS UTC 日期和時間設置為帶偏移的設備日期和時間格式

[英]Swift - iOS UTC date and time set with the device date and time format with offset

我是 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)

我在蘋果文檔中找到了一些方法,但不確定如何在我的代碼中實現。

參考

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 日期和時間轉換為帶偏移量的設備日期和時間格式

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)

試試這樣。 我猜語言環境將自動設置

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM