Swift: Date() to Milliseconds and Milliseconds to Date()

date from milliseconds in swift

To convert a Date object to milliseconds and milliseconds to Date object in Swift, extend the built-in Date class:

extension Date {
    var millisecondsSince1970: Int64 {
        Int64((self.timeIntervalSince1970 * 1000.0).rounded())
    }
    
    init(milliseconds: Int64) {
        self = Date(timeIntervalSince1970: TimeInterval(milliseconds) / 1000)
    }
}

Example usage:

// Today in milliseconds
Date().millisecondsSince1970 // 1641554695757

// The Date for 1 000 000 000 000 milliseconds
print(Date(milliseconds: 1_000_000_000_000)) // 2001-09-09 01:46:40 +0000

Let’s take a detailed look at why we want to do it this way and what is the 1970 thing.

How Does It Work

In Swift, you can extend existing types using the extension keyword and specifying the extended behavior.

In Swift, the Date type has a property called timeIntervalSince1970. This is the number of seconds since the 1970 epoch.

To convert seconds to milliseconds, you need to multiply the number of seconds by 1000.

To convert a Date to milliseconds, you could just call timeIntervalSince1970 and multiply it by 1000 every time. However, this introduces unnecessary repetition in your code. Instead, you can extend the implementation of the built-in Date type to support multiplying the date time intervals by 1000.

To do this, you can use the following extension:

extension Date {
    var millisecondsSince1970: Int64 {
        Int64((self.timeIntervalSince1970 * 1000.0).rounded())
    }
}

The reason why we use Int64 and not Int is because the number of milliseconds is great enough to be out of range in older 32-bit integer iOS systems. In those systems, the Int is a 32-bit integer whose max value is way less than the current time since 1970 in milliseconds.

Anyway, now it is possible to convert Date objects to milliseconds since 1970.

Next, let’s also make it possible to convert milliseconds back to Date objects.

The built-in Date type already supports converting seconds to date objects by using the Date(timeIntervalSince1970:) initializer.

To convert milliseconds to seconds, divide the number of milliseconds by 1000 and then call the Date(timeIntervalSince1970:) with the resulting seconds.

To avoid having to do this every time, you can write an extension to do it.

Let’s write an additional init() method to the Date type.

extension Date {
    init(milliseconds: Int64) {
        self = Date(timeIntervalSince1970: TimeInterval(milliseconds) / 1000)
    }
}

This initializer:

  1. Takes a number of milliseconds as an argument.
  2. Converts the milliseconds to seconds.
  3. Creates a Date object from seconds using Date(timeIntervalSince1970:).

Last but not least, let’s combine these two extensions such that we only have a single extension.

extension Date {
    var millisecondsSince1970: Int64 {
        Int64((self.timeIntervalSince1970 * 1000.0).rounded())
    }
    
    init(milliseconds: Int64) {
        self = Date(timeIntervalSince1970: TimeInterval(milliseconds) / 1000)
    }
}

Now you have successfully extended the built-in Date struct to support creating Date objects from milliseconds and vice versa.

Now you can use this extended behavior with Date objects anywhere in your code.

// Today in milliseconds
Date().millisecondsSince1970 // 1641554695757

// The Date for 1 000 000 000 000 milliseconds
print(Date(milliseconds: 1_000_000_000_000)) // 2001-09-09 01:46:40 +0000

Why 1970 Is a Thing?

Jan 1st, 1970 is a commonly used starting point for the time in computers. This 0-date at 1970 is called the Unix Epoch.

But why is there such starting point in time?

Computers need to be able to know a starting value for any quantity. You cannot just add values on top of some unspecified value. Time being no exception. Back in the early days of Unix, it was agreed that the starting point in time is Jan 1st, 1970.

To learn more about Unix Epoch and other popular epochs, feel free to read this article.

Conclusion

Today you learned how to convert Date to milliseconds and milliseconds to Date in Swift.

To recap, all you need is to extend the built-in Date struct with:

  • Functionality to convert seconds since 1970 to milliseconds.
  • An initializer that accepts a number of milliseconds, converts it to seconds and creates a Date from it.

Thanks for reading.

Happy coding!

Further Reading

Why 1970 Is the Starting Point in Time

Share this article with others:

Share on twitter
Share on linkedin
Share on facebook
Share on pinterest
Share on email

Learn these 10 tips to write professional code.

 

Make your coding life easier with these amazing command-line tools

 

Learn how to use latest advancements in AI to write faster.