Skip to content
DeveloperMemos

How to Get Milliseconds from a Date in Swift

Swift, Date, Time, Unix Timestamp1 min read

In Swift, working with dates and times can be essential for many applications, and sometimes we need to retrieve milliseconds from a given date. In this article, we will explore various ways to get milliseconds from a Date in Swift.

Understanding Dates in Swift

Before we dive into how to get milliseconds from a Date, let's first understand how Dates are represented in Swift.

In Swift, dates are represented by the Date struct. It represents a specific point in time, independent of any particular calendar or time zone. The Date struct stores a TimeInterval value that represents the number of seconds since January 1, 1970, at 00:00:00 UTC.

Astro(ASO Tool)

If you're looking to increase your app's visibility, Astro is the tool for you. You can track your app's keyword rankings for multiple countries all at the same time. I've been using it for a few months now and it's been a game-changer for me. I highly recommend it! 🚀

We earn a commission if you make a purchase, at no additional cost to you.

Retrieving Milliseconds from a Date

To get milliseconds from a Date in Swift, we first need to convert the date into a Unix timestamp. A Unix timestamp represents the number of seconds since January 1, 1970, at 00:00:00 UTC.

Once we have the Unix timestamp, we can multiply it by 1000 to get the number of milliseconds. Here's an example of how to get the milliseconds from a Date in Swift:

1let date = Date()
2let milliseconds = Int(date.timeIntervalSince1970 * 1000)
3print(milliseconds)

In the code above, we first create a new instance of Date. We then use the timeIntervalSince1970 property to get the Unix timestamp of the date, which is a TimeInterval value. We multiply the timeIntervalSince1970 value by 1000 to convert it into milliseconds, and then we cast it to an Int.

Using Foundation's DateFormatter

If you need to format a date string that includes milliseconds, you can use Foundation's DateFormatter class. Here's an example of how to use DateFormatter to get a date string that includes milliseconds:

1let date = Date()
2let formatter = DateFormatter()
3formatter.dateFormat = "yyyy-MM-dd HH:mm:ss.SSS"
4let dateString = formatter.string(from: date)
5print(dateString)

In the code above, we first create a new instance of Date. We then create a new instance of DateFormatter and set its dateFormat property to include milliseconds. Finally, we call the string(from:) method on the formatter to get the date string that includes milliseconds.

Conclusion

In conclusion, getting milliseconds from a Date in Swift is a simple task. We can convert the date into a Unix timestamp and then multiply it by 1000 to get the number of milliseconds. We can also use Foundation's DateFormatter class to format a date string that includes milliseconds. With these tools, we can easily work with dates and times in our Swift applications.