Swift convert unix time to date and time
Master System Design with Codemia
Enhance your system design skills with over 120 practice problems, detailed solutions, and hands-on exercises.
Introduction
Unix time stores a moment as the number of seconds since 1970-01-01 00:00:00 UTC. In Swift, converting that value into a readable date is straightforward once you separate two steps: first create a Date, then format it for the locale and time zone you want to show.
Convert Seconds to Date
If your timestamp is already in seconds, use Date(timeIntervalSince1970:).
Date represents an absolute point in time, not a preformatted calendar string. That is why the next step is formatting, not more conversion.
Format the Date for Display
Use DateFormatter when you want a user-facing string.
This is the usual pattern in apps: timestamps come from the network or database, then the formatter turns them into something readable for the current user.
Watch Out for Milliseconds
Many APIs return Unix time in milliseconds rather than seconds. If you pass milliseconds directly into timeIntervalSince1970, the date will be wildly wrong because Swift expects seconds.
If you ever see a year far in the future or far in the past, a seconds-versus-milliseconds mistake is one of the first things to check.
Extract Calendar Components
Sometimes you do not want a formatted string. You want the parts of the date such as year, month, and hour. Use Calendar for that.
This is useful for grouping records by day, showing relative UI, or building custom date labels.
Time Zone and Locale Are Presentation Concerns
The Unix timestamp itself is not tied to a local time zone. It represents one absolute instant. Time zone matters only when you choose how to display that instant.
If you want UTC specifically:
That distinction helps avoid bugs where developers think the timestamp needs to be "converted to UTC" before creating the Date. The Date already represents the instant correctly. Only the display changes.
Common Pitfalls
The most common mistake is confusing milliseconds with seconds. Always check the API contract before converting.
Another mistake is assuming Date itself stores a local string representation. It does not. Formatting is a separate concern handled by DateFormatter or related APIs.
Developers also sometimes hardcode a date format without setting locale or time zone intentionally. That can produce surprising output when the app runs in a different region or when UTC output was actually required.
Finally, avoid creating expensive formatters repeatedly in hot UI paths if performance matters. Reusing formatters is often better in list-heavy screens.
Summary
- Use
Date(timeIntervalSince1970:)for Unix timestamps in seconds. - Divide by
1000.0first when the input is in milliseconds. - Use
DateFormatterto turnDateinto a readable string. - Use
Calendarwhen you need date parts rather than formatted text. - Time zone affects presentation, not the underlying Unix timestamp.

