How to Use Timestamp in iOS Development
W

WhisperLink

timestamp
2025-09-17
How to Use Timestamp in iOS Development

How to Use Timestamp in iOS Development

iOS Timestamp

Getting Current Timestamp in iOS

Use Date().timeIntervalSince1970 to get the current Unix timestamp in seconds (Double). For milliseconds, multiply by 1000.

let timestamp = Date().timeIntervalSince1970 // Seconds  
let milliseconds = Int64(timestamp * 1000) // Milliseconds  

Converting Timestamp to Date

Use Date(timeIntervalSince1970:) to convert a timestamp back to a Date object.

let date = Date(timeIntervalSince1970: timestamp)  

Formatting Timestamps

Use DateFormatter to display timestamps in a readable format.

let formatter = DateFormatter()  
formatter.dateFormat = "yyyy-MM-dd HH:mm:ss"  
let dateString = formatter.string(from: date)  

For ISO8601 format, use ISO8601DateFormatter:

let isoFormatter = ISO8601DateFormatter()  
let isoString = isoFormatter.string(from: date)  

Timezone Handling

Always work in UTC for consistency, then convert to local time when displaying.

formatter.timeZone = TimeZone(abbreviation: "UTC")  

Storing Timestamps in Core Data

Use Double or Int64 attributes to store timestamps in Core Data.

@NSManaged var timestamp: Double  

Firebase Timestamps

Firebase provides FieldValue.serverTimestamp() for synchronized timestamps.

db.collection("events").document().setData([  
    "timestamp": FieldValue.serverTimestamp()  
])  

Comparing Timestamps

Use Calendar to compare dates accurately.

let calendar = Calendar.current  
let isSameDay = calendar.isDate(date1, inSameDayAs: date2)  

Performance Tips

  • Cache DateFormatter instances (they’re expensive to create).
  • Use ISO8601DateFormatter for better performance with ISO strings.

Common Issues

  • Precision: Unix timestamps are in seconds, but some APIs use milliseconds.
  • Timezone: Always verify if the timestamp is UTC or local time.
  • Debugging: Use po timestamp in Xcode’s console to inspect raw values.

This covers the essentials for working with timestamps in iOS. Apply these techniques for logging, API requests, and data storage.