Nsdate Timeintervalsince1970 Not Working in Swift

NSDate timeIntervalSince1970 not working in Swift?

1432233446145 most probably is a time interval given in milliseconds:

let date = NSDate(timeIntervalSince1970: 1432233446145.0/1000.0)
print("date is \(date)")
// date is 2015-05-21 18:37:26 +0000

Swift 3 and later:

let date = Date(timeIntervalSince1970: 1432233446145.0/1000.0)

Swift: Precision with timeIntervalSince1970

The issue there is that DateFormatter is limited to milliseconds. There is no way to display more than 3 fraction digits using it.

extension Formatter {
static let iso8601withFractionalSeconds: DateFormatter = {
let formatter = DateFormatter()
formatter.calendar = Calendar(identifier: .iso8601)
formatter.locale = Locale(identifier: "en_US_POSIX")
formatter.timeZone = TimeZone(secondsFromGMT: 0)
formatter.dateFormat = "yyyy-MM-dd'T'HH:mm:ss.SSSSSSSSSXXXXX"
return formatter

Formatter.iso8601withFractionalSeconds.string(from: Date())  // "2020-10-29T16:12:27.111000000Z"

If you would like to get the initial value back you just need top get the timeIntervalSince1970 from your convertedTime date:

let epochTime: TimeInterval = 1597269862.9328
print("\(epochTime) Precise Epoch Time")

let convertedTime = Date(timeIntervalSince1970: epochTime)
print("\(convertedTime) Time converted To Swift Date")

print(convertedTime.timeIntervalSince1970) // "1597269862.9328\n"

Note that Swift Date is stored as the time interval since reference date. If you would like to preserve the date accuracy you should use timeIntervalSinceReferenceDate instead of timeIntervalSince1970 when archiving it. Check this post.

timeIntervalSince1970 issue in Swift 3

You forgot the argument-label value in NSNumber's initializer:

let timeStamp = NSNumber(value: Date().timeIntervalSinceNow)

Have a look at the documentation of NSNumber: https://developer.apple.com/reference/foundation/nsnumber/1407545-init

Additionally, you don't need to convert the TimeInterval returned by timeIntervalSinceNow to an Int. TimeInterval is a typealias of Double and there is an initializer to create a NSNumber from a Double.

How to convert from NSDate(timeIntervalSince1970 to NSDate()?

In Swift 3, NSCalendar.current returns a Calendar, which is the
Swift value wrapper type for the Foundation NSCalendar type.

dateComponents() takes a Set<Calendar.Component> and two Date arguments. Date is the Swift value wrapper type for NSDate.

When existing Foundation APIs are imported into Swift, the types are bridged automatically, that why NSCalendar.current
returns a Calender and not NSCalendar.

The values types are preferred in Swift 3 because they
provide proper value semantics and use let and var instead
of immutable and mutable variants.

Putting it all together:

let fromDate = Date(timeIntervalSince1970: ...)
let toDate = Date()
let components = Set<Calendar.Component>([.second, .minute, .hour, .day, .weekOfMonth])
let differenceOfDate = Calendar.current.dateComponents(components, from: fromDate, to: toDate)

For more information about Swift 3 value wrapper types and
their corresponding Foundation types, see
SE-0069 Mutability and Foundation Value Types,
or the section "Bridged Types" in
Working with Cocoa Frameworks in the "Using Swift with Cocoa and Objective-C"

`[[NSDate date] timeIntervalSince1970]` in (C) free function always returns same value

The issue is that NSTimeInterval (which is what timeIntervalSince1970 returns) is a double and you’re casting it to a float. But float can only capture roughly 7 significant digits. That’s not nearly accurate enough to capture the number of seconds since 1970, much less the number of milliseconds.

Your lambda solution works simply because you removed the float cast. You can do the same with your function:

double now_ms() {
return 1000.0 * [[NSDate date] timeIntervalSince1970];

Unix dateTime format not properly converted in swift 5

Seems like you are getting milliseconds that you need to convert to seconds before creating date as,

let time: TimeInterval = 1570088096210/1000
let dateFinal = Date(timeIntervalSince1970: time)

2019-10-03 07:34:56 +0000

How to create a time stamp from nsdate(timeintervalsince1970)

What you are looking for is DateComponentsFormatter. You can look at the different formatters Foundation offers, here.

If you want to have a string that denotes the amount of time that has elapsed since a given date, you can say something like:

if let seconds = posts[visibli.row].timeStamp {
let time = Date(timeIntervalSince1970: TimeInterval(seconds))
let dateComponentsFormater = DateComponentsFormatter()
dateComponentsFormater.unitsStyle = .positional
let string = dateComponentsFormater.string(from: time, to: Date())
labelTime.text = string

(Swift) timeIntervalSince1970 stored in Realm with current dateTime, but showing wrong date when it is read?

Update your getCurrentTimeIntervalSince1970 func to this

func getCurrentTimeIntervalSince1970() -> Int {
return Int(Date().timeIntervalSince1970)

let date = getCurrentTimeIntervalSince1970()
debugPrint(Date(timeIntervalSince1970: Double(date)))



2020-02-26 10:05:43 +0000

Date(timeIntervalSince1970:) returns 2 different results

The timeIntervalSince1970 initializer sets up the time in the UTC timezone, while your API might be sending dates in GMT. When you are using print(data), you have different results, because if you are not using a DateFormatter to generate the String format of the Date object, it uses your devices current settings when formatting the Date object.

A Date object represents an absolute point in time, but when you are printing it with a DateFormatter, it gets converted into a location/time zone specific, relative representation. You just have to set up your DateFormatter to match the time zone settings of your API and you will see the dates correctly printed.

Dates are not equal while using timeIntervalSince1970

The problem is the usage of timeIntervalSince1970. If you use this, the Date implementation will do some Double calculations to align it to the reference date (2001-01-01).

If you use timeIntervalSinceReferenceDate instead, this will be used directly, and your code should work then:

for i in 1...200000 {
let date1 = Date()
let date2 = Date(timeIntervalSinceReferenceDate: date1.timeIntervalSinceReferenceDate)
if (date1 != date2) {
// never called on my machine:
let delta = date1.timeIntervalSince(date2)
print("\(i): \(delta)")

For your information, here the interesting parts of struct Date implementation on https://github.com/apple/swift-corelibs-foundation/blob/master/Foundation/Date.swift - you see the calculation done in the first init:

public struct Date : ReferenceConvertible, Comparable, Equatable {

fileprivate var _time: TimeInterval
public static let timeIntervalBetween1970AndReferenceDate: TimeInterval = 978307200.0

public init(timeIntervalSince1970: TimeInterval) {
self.init(timeIntervalSinceReferenceDate: timeIntervalSince1970 - Date.timeIntervalBetween1970AndReferenceDate)
public init(timeIntervalSinceReferenceDate ti: TimeInterval) {
_time = ti

Related Topics

Leave a reply