Swift Date Milliseconds: Converting, Formatting and Sharing Time Values Safely
How Swift Date maps to milliseconds, what conversion and formatting change, and when an epoch integer or a localized clock string is the better choice.
Developers often need a Swift Date expressed in milliseconds: an integer for an API, a timestamp in a log, or a clock reading with three fractional digits on screen. Each of these is a transformation of the same value, and each has different effects on precision, readability and reuse. This review covers what each conversion changes and when a plain representation is the better choice. No product-specific measurements or test results were supplied for this article, so the guidance relies on documented Foundation behavior and general principles. Points that need checking in your own environment are flagged.
Is converting a Date to milliseconds suitable for your use?
Recommendation: use an integer count of milliseconds since the Unix epoch when the value moves between systems, such as APIs, databases, analytics events or cross-language services. The main benefit is that the number is locale-neutral and unambiguous, provided both sides agree on the epoch and unit. The decisive tradeoff is that people cannot read it. A value like 1700000000000 says nothing to someone scanning a log, and it is easy to confuse with a seconds-based timestamp, which is a thousand times smaller.
A formatted clock string with milliseconds, such as hours, minutes, seconds and three fractional digits, suits displays and diagnostics where a person reads the time. Plain text with no millisecond component is often the better choice for general audiences. Most readers gain nothing from sub-second detail, and the extra digits add clutter and can be misread as part of the seconds field.
- Choose an epoch integer in milliseconds for machine exchange, storage and sorting.
- Choose an ISO 8601 string with fractional seconds when the value must be both machine-parseable and human-inspectable, for example in logs or JSON that people debug.
- Choose a localized clock string with fractional seconds for user-facing displays where sub-second timing matters, such as a stopwatch or race results.
- Choose plain localized time without milliseconds for ordinary user-facing times.
What the conversion actually changes
To avoid confusion with other text tools: this transformation does not reverse characters, mirror glyphs or substitute Unicode lookalike styles. It changes how a point in time is represented. The underlying moment stays the same, while the stored characters or numbers differ completely between representations.
How Date stores time
A Swift Date holds a TimeInterval, which is a Double counting seconds from Foundation's reference date of 1 January 2001, 00:00:00 UTC. The timeIntervalSince1970 property re-expresses that value relative to the Unix epoch of 1 January 1970 UTC, still in seconds and still as a Double. A Date carries no time zone and no calendar. Those are applied only when the value is formatted for display.
Numeric conversion to milliseconds
Getting milliseconds means multiplying the seconds value by 1000 and usually converting the result to an integer. That step is lossy. Anything finer than a millisecond is discarded. The choice of conversion also matters: Int(x) truncates toward zero, while rounded() rounds to the nearest value, so the two can differ by one millisecond. For dates before 1970 the interval is negative, and truncation then moves toward zero rather than toward the earlier millisecond. Use Int64 to make the width explicit, since millisecond epoch values exceed the 32-bit range.
import Foundation
let date = Date()
// Date -> milliseconds since 1970 (rounded to the nearest millisecond)
let millis = Int64((date.timeIntervalSince1970 * 1000).rounded())
// Milliseconds -> Date
let restored = Date(timeIntervalSince1970: TimeInterval(millis) / 1000)
// Arithmetic check: 1.5 seconds after the epoch is 1500 milliseconds
let sample = Date(timeIntervalSince1970: 1.5)
let sampleMillis = Int64((sample.timeIntervalSince1970 * 1000).rounded()) // 1500
A Date restored from milliseconds may not compare equal to the original with ==, because the original likely held sub-millisecond precision. When testing round trips, compare the millisecond integers or allow a tolerance.
Formatting milliseconds as text
Formatting turns the Date into a string, and the result depends on the formatter, pattern, locale and time zone. With DateFormatter, the pattern letters SSS produce three fractional-second digits. For fixed machine formats, set the locale to en_US_POSIX and set an explicit time zone. Otherwise user settings, such as a 12-hour clock preference or a non-Gregorian calendar, can alter the output.
let fixed = DateFormatter()
fixed.locale = Locale(identifier: "en_US_POSIX")
fixed.timeZone = TimeZone(identifier: "UTC")
fixed.dateFormat = "yyyy-MM-dd'T'HH:mm:ss.SSS'Z'"
let stamp = fixed.string(from: date)
let iso = ISO8601DateFormatter()
iso.formatOptions = [.withInternetDateTime, .withFractionalSeconds]
let isoStamp = iso.string(from: date)
On newer OS versions, Date.FormatStyle offers a localized route. For example, .dateTime.hour().minute().second().secondFraction(.fractional(3)) asks for a clock reading with three fractional digits, arranged according to the user's locale. The ISO 8601 format style also has an option to include fractional seconds. Check the minimum deployment target for each API against the Apple documentation for the SDK you build with.
| Representation | What is stored | Human-readable | Locale-dependent | Typical use |
| Epoch milliseconds (Int64) | A single integer | No | No | APIs, storage, sorting |
| ISO 8601 with fractional seconds | Fixed-pattern string, usually UTC | Partly | No, if configured as shown | Logs, JSON, interchange people inspect |
| Localized clock string with fractions | Display text shaped by locale settings | Yes | Yes | User-facing timers and results |
| Localized time without milliseconds | Display text | Yes | Yes | General user-facing times |
Encoding milliseconds in JSON
JSONEncoder and JSONDecoder support millisecondsSince1970 as a date encoding and decoding strategy, which handles the conversion for Codable types. Both sides must use the same strategy. A decoder set to seconds will read a millisecond value as a date far in the future, and the reverse produces a date near 1970. These failures are silent, so a mismatch shows up as wrong data rather than an error.
Will the result stay readable and usable after copying or sharing?
Epoch integers copy and paste cleanly because they contain only digits. The risk is interpretation, not corruption. A pasted number carries no label saying it is milliseconds or which epoch it uses. Wherever the value leaves its original context, label the unit in field names, column headers or documentation, for example createdAtMs.
ISO 8601 strings also survive copying well and can be parsed again by most date libraries. Two details can break parsing elsewhere: whether fractional seconds are present, and whether the string ends in Z or a numeric offset. If a receiving system rejects fractional seconds, either remove them or confirm what that system accepts before sending.
Localized clock strings are the least portable. Digit order, the 12- or 24-hour clock, AM/PM markers and possibly the separator before the fractional digits vary by locale. A string pasted from one user's device may not parse on another's. Treat localized output as display-only, and keep the Date or the epoch integer as the authoritative value for any further processing.
Accessibility, search and editing
A bare millisecond integer is hard to use with assistive technology. A screen reader is likely to read it as one very large number or digit by digit, and neither tells the listener when the event happened. For user-facing interfaces, show a formatted time and keep the raw integer out of the visible and spoken text. This article has no documentation or scoped test of how VoiceOver or other screen readers announce fractional-second clock strings. If that matters for your app, test with the assistive technologies and locales you support, and consider an accessibility label that states the time in words when the visual format is dense.
For search and editing, consistent machine formats help. Fixed-width ISO 8601 strings in UTC sort correctly as text and are easy to find in logs. Epoch integers sort numerically but are hard to search by date without converting them. Localized strings neither sort nor search reliably across locales.
Evidence gaps
- No benchmarks, device tests or sample datasets were supplied, so this article makes no claims about formatter performance or measured rounding error rates.
- Behavior of specific receiving systems, such as particular databases, analytics platforms or third-party APIs, was not tested. Confirm each one's expected unit and format.
- Screen reader output for millisecond clock strings was not verified and should be tested in your target environments.
- API availability by OS version should be checked against current Apple documentation rather than assumed.