138

How do you get the seconds from epoch in Swift?

Chris Redford
  • 16,982
  • 21
  • 89
  • 109
  • 2
    Same as in Objective-C - use NSDate. – gnasher729 Aug 02 '14 at 15:32
  • 2
    I have avoided developing Apple products because I hate Objective-C. Consequently, I haven't learned it. And I know that the Swift syntax is at least slightly different. Just show me the syntax. Get yourself some easy SO reputation. – Chris Redford Aug 02 '14 at 15:35
  • 3
    https://developer.apple.com/library/prerelease/mac/documentation/Cocoa/Reference/Foundation/Classes/NSDate_Class/index.html#//apple_ref/occ/instm/NSDate/timeIntervalSince1970 – Martin R Aug 02 '14 at 15:37
  • 1
    Care to explain the downvotes? – Chris Redford Aug 02 '14 at 15:43
  • 1
    Asking for code, not looking to learn, particularly your previous comment WRT "easy SO ". – zaph Aug 02 '14 at 15:44
  • I'm looking to learn the code. Which is why I'm asking for it. This question has an upvote of 106 and asks the exact same question, just in C# instead of Swift: http://stackoverflow.com/questions/2883576/how-do-you-convert-epoch-time-in-c – Chris Redford Aug 02 '14 at 15:48
  • Looks like I'm going to need moderator. – Chris Redford Aug 02 '14 at 15:50
  • Moderator, why? Because your question was down voted? – zaph Aug 02 '14 at 15:51
  • Because the people who are downvoting it (at least you) don't believe SO should have consistent standards. So your vote is apparently based on random haphazard standards. – Chris Redford Aug 02 '14 at 15:53
  • If this question is so easy to answer, why wouldn't someone just answer it? – Chris Redford Aug 02 '14 at 15:56
  • Actually @Martin did answer the question in a comment above. – zaph Aug 02 '14 at 16:00
  • No, Martin linked to a gigantic reference page. More helpful than your contributions but still doesn't answer the question. See Yannik's answer below as an example of what an answer looks like. – Chris Redford Aug 02 '14 at 16:02
  • 4
    No, it links directly to the entry for the Swift method: `- timeIntervalSince1970`. – zaph Aug 02 '14 at 16:07
  • 3
    Actually I linked to the specific method :) – Martin R Aug 02 '14 at 16:07
  • Apple's website formatting didn't make that clear. While I appreciate it, it still isn't as clear as the way Yannik answered, especially for someone learning a new language. – Chris Redford Aug 02 '14 at 16:12
  • In Sumit Oberoi's response (based on CHIP-love-NY comment)... 1000 millisecond = 1 seconds. You should divide by 1000 to get seconds. Should be: In seconds:Int(Date().timeIntervalSince1970 / 1000) – P. Stern Feb 23 '19 at 07:13

5 Answers5

197

You can simply use NSDate's timeIntervalSince1970 function.

let timeInterval = NSDate().timeIntervalSince1970
some_id
  • 29,466
  • 62
  • 182
  • 304
Yannik
  • 2,463
  • 2
  • 16
  • 7
104

For Swift 3.0

Date().timeIntervalSince1970
Martin R
  • 529,903
  • 94
  • 1,240
  • 1,382
Sumit Oberoi
  • 3,455
  • 2
  • 18
  • 18
  • 2
    Good one. Also, folks may be interested in http://stackoverflow.com/questions/39811352/swift-3-date-vs-nsdate – Matt Johnson-Pint Jan 08 '17 at 21:10
  • 13
    @CHiP-love-NY: That is not true. [Unix time](https://en.wikipedia.org/wiki/Unix_time) is the number of **seconds** since 1 January 1970, UTC. – Martin R Feb 23 '19 at 13:48
  • 3
    It returns a [TimeInterval](https://developer.apple.com/documentation/foundation/timeinterval), which is in secods – Daniel Nov 18 '19 at 16:11
13

You can get that using following

Int(Date().timeIntervalSince1970)

This is for current date, if you want to get for a given date

Int(myDate.timeIntervalSince1970)

If you want to convert back from UNIX time epoch to Swift Date time, you can use following

let date = Date(timeIntervalSince1970: unixtEpochTime)
Mohammad Sadiq
  • 5,070
  • 28
  • 29
12

1 second = 1,000 milliseconds
1 second = 1,000,000 microseconds

Swift's timeIntervalSince1970 returns seconds with what's documented as "sub-millisecond" precision, which I've observed to mean usually microseconds but sometimes one scale (one digit to the right of the decimal) less or more. When it returns a scale of 5 (5 digits after the decimal), I assume Swift couldn't produce 6 scales of precision, and when it returns a scale of 7, that extra digit can be truncated because it's beyond microsecond precision. Therefore:

let secondPrecision = Int(Date().timeIntervalSince1970) // definitely precise
let millisecondPrecision = Int(Date().timeIntervalSince1970 * 1_000) // definitely precise
let microsecondPrecision = Int(Date().timeIntervalSince1970 * 1_000_000) // most-likely precise

All that said, millisecond-precision is the true Unix timestamp and the one that, I think, everyone should use. If you're working with an API or a framework that uses the Unix timestamp, most likely it will be millisecond-precise. Therefore, for a true Unix timestamp in Swift:

typealias UnixTimestamp = Int

extension Date {
    /// Date to Unix timestamp.
    var unixTimestamp: UnixTimestamp {
        return UnixTimestamp(self.timeIntervalSince1970 * 1_000) // millisecond precision
    }
}

extension UnixTimestamp {
    /// Unix timestamp to date.
    var date: Date {
        return Date(timeIntervalSince1970: TimeInterval(self / 1_000)) // must take a millisecond-precise Unix timestamp
    }
}

let unixTimestamp = Date().unixTimestamp
let date = unixTimestamp.date

Note that in the year 2038, 32-bit numbers won't be usable for the Unix timestamp, they'll have to be 64-bit, but Swift will handle that for us automatically so we can safely use Int (and need not use Int64 explicitly).

trndjc
  • 11,654
  • 3
  • 38
  • 51
2

If you don't want to import Foundation, i.e. for Linux use etc, you can use the following from CoreFoundation:

import CoreFoundation

let timestamp = CFAbsoluteTimeGetCurrent() + kCFAbsoluteTimeIntervalSince1970
rshev
  • 4,086
  • 1
  • 23
  • 32
  • 1
    Do you know when things might Date and friends will become cross-platform? – Zoltán Matók Aug 05 '20 at 16:03
  • @ZoltánMatók I've heard they have plans to reimplement more of Foundation in the open. Take a look at forums.swift.org for more info. – rshev Aug 06 '20 at 23:13