問(wèn)題描述
我正在嘗試制作一個(gè)考勤應(yīng)用程序,但我對(duì) iOS 和 Firebase 中的日期和時(shí)間感到非常困惑.
I'm trying to make an attendance app and I am really confused about date and time in iOS and Firebase.
我使用日期作為 Key,這是我的 Firebase 數(shù)據(jù)庫(kù)的結(jié)構(gòu).
I use date as Key, this is the structure of my Firebase database.
--Employees
--Unique_ID
--Details
Name: John
--Attendance
--dateToday
Timein: 8:00 AM
Timeout: 5:00 PM
BreakStart: 12:00 PM
BreakFinish: 1:00 PM
這是獲取我用作密鑰的日期時(shí)間戳的代碼
This is my code to get the date timestamp I used as Key
override func viewDidLoad() {
super.viewDidLoad()
let now = NSDate()
let nowTimeStamp = self.getCurrentTimeStampWOMiliseconds(dateToConvert: now)
// I save this dateToday as Key in Firebase
dateToday = nowTimeStamp
}
func getCurrentTimeStampWOMiliseconds(dateToConvert: NSDate) -> String {
let objDateformat: DateFormatter = DateFormatter()
objDateformat.dateFormat = "yyyy-MM-dd"
let strTime: String = objDateformat.string(from: dateToConvert as Date)
let objUTCDate: NSDate = objDateformat.date(from: strTime)! as NSDate
let milliseconds: Int64 = Int64(objUTCDate.timeIntervalSince1970)
let strTimeStamp: String = "(milliseconds)"
return strTimeStamp
}
但是當(dāng)我將它轉(zhuǎn)換回日期時(shí),我得到 2017-09-22 16:00:00 +0000,這是錯(cuò)誤的,因?yàn)樵谖业奈恢檬?9 月 23 日.
But when I convert it back to date I get 2017-09-22 16:00:00 +0000, which is wrong because it is 23rd of September in my location.
什么是正確的代碼,以便我可以獲得正確的日期時(shí)間戳和時(shí)間時(shí)間戳?
What is the right code to use so that I can get the correct date timestamp and time timestamp?
推薦答案
為了將當(dāng)前時(shí)間保存到 firebase 數(shù)據(jù)庫(kù),我使用了 Unic Epoch Conversation:
For saving Current time to firebase database I use Unic Epoch Conversation:
let timestamp = NSDate().timeIntervalSince1970
用于將 Unix 紀(jì)元時(shí)間解碼為 Date().
and For Decoding Unix Epoch time to Date().
let myTimeInterval = TimeInterval(timestamp)
let time = NSDate(timeIntervalSince1970: TimeInterval(myTimeInterval))
這篇關(guān)于iOS Swift - 獲取當(dāng)前本地時(shí)間和日期時(shí)間戳的文章就介紹到這了,希望我們推薦的答案對(duì)大家有所幫助,也希望大家多多支持html5模板網(wǎng)!