如何从Firebase的ServerValue获取时间戳?服务器本地时间获取方法
ServerValue.timestamp() Doesn't Return TimeInterval & How to Get Server Local Time Hey there! Let's break this down for you clearly.
Why the Error Occurs
First off, ServerValue.timestamp() doesn't spit out a raw timestamp value (like TimeInterval or an integer) — it’s actually a placeholder dictionary ([AnyHashable: Any]). This placeholder tells Firebase Realtime Database: "When you write this data to the server, replace me with the server’s current UTC timestamp (in milliseconds)."
Since it’s a dictionary, trying to divide it by 1000 (an integer) throws that "binary operator cannot be applied" error — you can’t do arithmetic on a dictionary and a number!
How to Get the Actual Server Timestamp
To get the real server timestamp value, you need to write the placeholder to the database first, then read back the value Firebase replaces it with. Here’s a working Swift example:
import FirebaseDatabase let dbRef = Database.database().reference() let tempTimestampNode = dbRef.child("temp_server_timestamp") // Step 1: Write the placeholder to the database tempTimestampNode.setValue(ServerValue.timestamp()) { error, ref in guard error == nil else { print("Failed to write timestamp: \(error!.localizedDescription)") return } // Step 2: Read back the actual server timestamp tempTimestampNode.observeSingleEvent(of: .value) { snapshot in guard let serverTimestampMs = snapshot.value as? Int64 else { print("Couldn’t parse server timestamp") return } // Convert milliseconds to a UTC Date object let utcDate = Date(timeIntervalSince1970: TimeInterval(serverTimestampMs) / 1000) print("Server UTC time: \(utcDate)") // Optional: Clean up the temporary node if you don’t need it tempTimestampNode.removeValue() } }
How to Convert Server Time to a Local Time Zone
The server timestamp is in UTC by default. To convert it to a specific local time (like your user’s device time zone or a fixed zone), use DateFormatter and set the desired time zone:
// Inside the observeSingleEvent closure, after getting utcDate: let dateFormatter = DateFormatter() dateFormatter.timeZone = TimeZone(identifier: "Asia/Shanghai") // Replace with your target time zone dateFormatter.dateStyle = .full dateFormatter.timeStyle = .full let localTimeString = dateFormatter.string(from: utcDate) print("Server time converted to Shanghai local time: \(localTimeString)")
If you want to use the device’s current time zone automatically, just skip setting the timeZone property — DateFormatter uses the device’s default time zone by default.
内容的提问来源于stack exchange,提问作者Difeng Chen

