[英]Swift NSDateFormatter not using correct locale and format
這是我的代碼:
let currentDate = NSDate()
let usDateFormat = NSDateFormatter()
usDateFormat.dateFormat = NSDateFormatter.dateFormatFromTemplate("d MMMM y", options: 0, locale: NSLocale(localeIdentifier: "en-US"))
cmt.date = usDateFormat.stringFromDate(currentDate)
我期待得到“2015 年 10 月 15 日”,但我得到了“2015 年 10 月 15 日”。 本月采用瑞典語。
我做錯了什么? 語言環境和格式都是錯誤的。
嘗試這個:
let dateString = "2015-10-15"
let formater = NSDateFormatter()
formater.dateFormat = "yyyy-MM-dd"
print(dateString)
formater.locale = NSLocale(localeIdentifier: "en_US_POSIX")
let date = formater.dateFromString(dateString)
print(date)
斯威夫特 3 Xcode 8
let dateString = "2015-10-15"
let formater = DateFormatter()
formater.dateFormat = "yyyy-MM-dd"
print(dateString)
formater.locale = Locale(identifier: "en_US_POSIX")
let date = formater.date(from: dateString)
print(date!)
我希望它有幫助。
查看dateFormatFromTemplate
的文檔。 它指出:
返回值
一個本地化的日期格式字符串,表示模板中給定的日期格式組件,根據 locale 指定的區域設置適當排列。
返回的字符串可能不完全包含模板中給出的那些組件,但可能——例如——應用了特定於區域設置的調整。
這就是安排和語言的問題。 要獲取您要查找的日期,您需要按如下方式設置日期格式化程序的dateFormat
和locale
:
let currentDate = NSDate()
let usDateFormat = NSDateFormatter()
usDateFormat.dateFormat = "d MMMM y"
usDateFormat.locale = NSLocale(localeIdentifier: "en_US")
cmt.date = usDateFormat.stringFromDate(currentDate)
更好的 Swift 3/3.1 解決方案:
let dateFormatter = DateFormatter()
dateFormatter.locale = Locale(identifier: "en_US")
試試這個代碼
let locale1:Locale = NSLocale(localeIdentifier: "en_US") as Locale
var date = Date().description(with: locale1)
print(date)
//2017 年 4 月 3 日星期一...
你可以在 Swift5 中使用 Date 擴展:
extension Date {
var timestamp: String {
let dataFormatter = DateFormatter()
dataFormatter.locale = Locale(identifier: "en_US_POSIX")
dataFormatter.dateFormat = "yyyy-MM-dd HH:mm:ss.SSSS"
return String(format: "%@", dataFormatter.string(from: self))
}
}
您可以通過以下方式獲取時間戳
print("Now: \(Date().timestamp)")
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.