Swift – Convert Timestamp to Human-readable Format
In this tutorial, we will learn how to convert a timestamp to a human-readable format in Swift. We will use the Date
and DateFormatter
classes to achieve this, along with practical examples for formatting the converted date.
What is a Timestamp?
A timestamp is a numeric representation of a specific point in time, typically measured in seconds or milliseconds since January 1, 1970 (known as the Unix epoch). Timestamps are widely used in programming for date and time manipulation.
For example:
- The timestamp
1698316800
represents2023-10-26 10:40:00 +0000
. - The timestamp
0
represents1970-01-01 00:00:00 UTC
.
To make timestamps more user-friendly, we convert them into a human-readable format.
Steps to Convert Timestamp to Human-readable Format
- Convert the timestamp into a
Date
object. - Use the
DateFormatter
class to format theDate
object into a human-readable string.
Let’s implement these steps in Swift.
Convert Timestamp to Date
To convert a timestamp into a Date
object, initialize a Date
with the timestamp in seconds. For example:
main.swift
import Foundation
let timestamp: TimeInterval = 1698316800
let date = Date(timeIntervalSince1970: timestamp)
print("Date: \(date)")
In this example, the timestamp 1698316800
is converted into a Date
object representing 2023-10-26 10:40:00 +0000
.
Output
Date: 2023-10-26 10:40:00 +0000
Program ended with exit code: 0